[Effective Kotlin] : 8장 효율적인 컬렉션 처리

0

컬렉션이 없는 어플리케이션은 상상하기 어렵다.
뉴스나, 제품리스트, 카테고리 리스트, 다양한 곳에 컬렉션들이 사용되고 있다.

코틀린은 강력한 컬렉션 처리를 지원한다.

Before

    val news = listOf<News>(News(true, "", 30))
    val visibleNews = mutableListOf<News>()
    for (n in news) {
        if (n.visible) {
            visibleNews.add(n)
        }
    }

    Collections.sort(visibleNews, { n1, n2 ->
        n2.publishedAt - n1.publishedAt
    })
    val newsItemAdpater = mutableListOf<NewsItemAdapter>()
    for (n in visibleNews){
        newsItemAdpater.add(NewsItemAdapter(n))
    }

After

    val newsItemAdapters = news.filter { it.visible}
    .sortedBy {it.publishedAt}.map(::NewsItemAdapter)

코드를 보면 짧아질뿐 아니라, 가독성 측면에서도 향상된다.

둘의 성능 차이는 없으나 아래의 코드는 성능 차이가 발생한다.

//Sequence가 들어가면서 속도가 줄어든 코드 
fun ProductsSequenceProcessing() : String{
    return clientList.asSequence()
        .filter {it.adult}
        .flatMap {it.products.asSequence() }
        .filter {it.bought}
        .mapNotNull {it.price}
        .joinToString(separator = "+") {"$$it"}
}

fun productsListProcessing(): String {
    return clientList.filter { it.adult }
        .flatMap {it.products}
        .filter{it.bought}
        .map {it.price}
        .filterNotNotNull()
        .map {"$$it"}
        .joinToString(separator = "+")
}

컬렉션 처리 최적화는 어렵지만 굉장히 중요하다.

프론트 클라이언트를 구현할때, 컬렉션 처리가 성능에 문제를 일으키는 경우가 많다.

그래도 다행인것은 몇가지 규칙을 지키면 된다는점이다.

이번장에서는 이와 관련된 내용을 살펴보자.

profile
쉽게 가르칠수 있도록 노력하자

0개의 댓글