Skip to content

Latest commit

 

History

History
28 lines (24 loc) · 868 Bytes

컬렉션의 처리 단계 수를 제한하자.md

File metadata and controls

28 lines (24 loc) · 868 Bytes

컬렉션의 처리 단계 수를 제한하자

컬렉션 처리 메서드가 비용이 많이 드는 이유

  • 전체 컬렉션에 대한 반복 처리
  • 중간 컬렉션 및 객체 생성
따라서 적절한 컬렉션 처리 함수를 통해 처리 단계 수를 제한하는 것이 권장됨

처리 예시

// 01. worst case
fun List<Student>.getNames(): List<String> = this
    .map { it.name }
    .filter { it != null }
    .map { it!! }

// 02. better case
fun List<Student>.getNames(): List<String> = this
    .map { it.name }
    .filterNotNull()

// 03. best case
fun List<Student>.getNames(): List<String> = this
    .mapNotNull { it.name }
  • 어떤 컬렉션 처리 메서드가 있는지 확인하는 것이 유용
  • 안드로이드 스튜디오에서 경고를 통해 어떤 메서드가 권장되는지 어느 정도 알려줌