반응형
모든 컬렉션 처리 메서드는 내부적으로 요소들을 활용해 반복을 돌며, 내부적으로 계산을 위해 추가적인 컬렉션을 만들어 사용합니다.
시퀀스 처리도 시퀀스 전체를 랩하는 객체가 만들어지며, 조작을 위해서 또 다른 추가적인 객체를 만들어 냅니다.
요소의 수가 많다면, 큰 비용이 들어갈 수 있으므로, 컬렉션 처리 단계 수를 적절하게 제한하는 것이 좋습니다.
어떤 메서드를 사용하는지에 따라 컬렉션 처리의 단계 수가 달라집니다.
class Student(val name: String?)
// 작동은 한다.
fun List<Student>.getNames(): List<String> = this
.map { it.name }
.filter { it != null }
.map { it!! }
// 더 좋다.
fun List<Student>.getNames(): List<String> = this
.map { it.name }
.filterNotNull()
// 가장 좋다.
fun List<Student>.getNames(): List<String> = this
.mapNotNull { it.name }
다음 표는 두 단계 이상의 컬렉션 처리 함수를 한번에 끝내는 방법을 정리한 것입니다.
이 코드보다는 | 이 코드가 좋다. |
.filter { it != null } .map { it!! } |
.filterNotNull() |
.map { <Transformation> } .filterNotNull() |
.mapNotNull { <Transformation> } |
.map { <Transformation> } .joinToString() |
.joinToString { <Transformation> } |
.filter { <Transformation1> } .filter { <Transformation2> } |
.filter { <Predicate 1> && <Predicate 2> } |
.filter { it is Type } .map { it as Type } |
.filterIsInstancec<Type>() |
.sortedBy { <Key 1> } .sortedBy { <Key 2> } |
.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도 비슷하다.) |
반응형
'Kotlin > 이펙티브 코틀린' 카테고리의 다른 글
[이펙티브 코틀린] Item51. 성능이 중요한 부분에는 기본 자료형 배열을 사용하라 (0) | 2024.02.03 |
---|---|
[이펙티브 코틀린] Item49. 하나 이상의 처리 단계를 가진 경우에는 시퀀스를 사용하라 (1) | 2024.02.03 |
[이펙티브 코틀린] Item48. 더 이상 사용하지 않는 객체의 레퍼런스를 제거하라 (0) | 2024.01.28 |