공부/이펙티브코틀린
아이템 50 - 컬렉션 처리 단계 수를 제한하라
띵커베르
2024. 8. 18. 13:03
728x90
컬렉션 처리 메서드는 비용이 많이 든다.
적절한 메서드를 활용해서, 컬렉션 처리 단계 수를 적절하게 제한하는 것이 좋다
// 비효율적인 코드
val result = listOf(1, 2, 3, 4, 5)
.map { it * 2 }
.filter { it > 3 }
.map { it + 1 }
.filter { it < 10 }
// 최적화된 코드
val result = listOf(1, 2, 3, 4, 5)
.map { it * 2 }
.mapNotNull { if (it > 3 && it < 10) it + 1 else null }
.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> } |
728x90