본문 바로가기
개발/Java, Kotlin

[Effective Kotlin] Item 52: Limit the number of operations

by 달사쿠 2021. 10. 28.
반응형

모든 collection 처리 함수는 비용이 발생합니다. 

따라서 수집 처리 단계의 수를 제한하고, 주로 복합 작업을 사용하여 이를 수행합니다.

 

복합작업은 아래의 예를 보면 이해하기 쉽습니다.

 

1. null이 아닌 것을 필터링한 다음 2. null을 허용하지 않는 타입으로 캐스팅

하는 대신 filterNotNull을 사용합니다.

 

1. null을 매핑한 다음 2. 필터링

하는 대신 mapNotNull을 수행할 수 있습니다.

 

class Student(val name: String?)

// Works
fun List<Student>.getNames(): List<String> = this
   .map { it.name }
   .filter { it != null }
   .map { it!! }
 
// Better
fun List<Student>.getNames(): List<String> = this
   .map { it.name }
   .filterNotNull()

// Best
fun List<Student>.getNames(): List<String> = this
   .mapNotNull { it.name }

 

가장 큰 문제는 이러한 변경의 중요성에 대한 오해가 아니라, 어떤 collection 처리 함수를 사용해야 하는지에 대한 지식이 부족하기 때문에 이것들에 대해 공부할 필요가 있습니다.

 

더불어 더 나은 대안을 소개하도록 제안하는 warning도 도움이 됩니다.

 

반응형

아래는 작업 수를 제한하는 몇가지 일반적인 함수들 입니다!

 

Instead of: Use:
.filter { it != null }
.map { it!! }
.filterNotNull()
.map { <Transformation> }
.filterNotNull()
.mapNotNull { <Transformation> }
.map { <Transformation> }
.joinToString()
.joinToString { <Transformation> }
.filter { <Predicate 1> }
.filter { <Predicate 2> }
.filter { <Predicate 1> && <Predicate 2> }
.filter { it is Type }
.map { it as Type }
.filterIsInstance<Type>()
.sortedBy { <Key 2> }
.sortedBy { <Key 1> }
.sortedWith( compareBy( { <Key 1> }, { <Key 2> } ) )

listOf(...)
.filterNotNull()
listOfNotNull(...)
.withIndex()
.filter { (index, elem) -> <Predicate using index> }
.map { it.value }
.filterIndexed { index, elem -> <Predicate using index> }

(map, forEach, reduce, fold에서도 비슷하게 사용)

 


Summary

대부분의 컬렉션 처리 단계는 전체 컬렉션과 중간 컬렉션 생성에 대한 반복이 필요합니다.

이 비용은 보다 적합한 컬렉션 처리 함수를 사용해 제한할 수 있습니다.

반응형

댓글