Home > Software engineering >  Which one is more efficient using kotlin?
Which one is more efficient using kotlin?

Time:09-02

I have a collection with objects that contain a value field and I need reduce information objective which one is more efficent or better and why?.

 settings.filter {it.value != null }.forEach{
    doSomething ....
}

settings.forEach{
    if(it.value != null){
        doSomething ...
    }

CodePudding user response:

filter allocates a list, so the second one will be faster. But if your list isn’t many hundreds of items long, the difference is negligible and you should choose what you think is more readable code. In this case I think the second one is easier to read anyway.

CodePudding user response:

Here is the internal implementation of filter function used in Kotlin Collection.

public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
    return filterTo(ArrayList<T>(), predicate) // New Array List Object Creation
}

public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterTo(destination: C, predicate: (T) -> Boolean): C {
    for (element in this) if (predicate(element)) destination.add(element)
    return destination
}

Here you can see, it creates new list. It creates an empty arraylist and add filtered elements to new list.

Adding to Tenfour04's answer, for small list you can use filter as its more idiomatic. If you need to go with optimal way, you can use non null check.

Also you do this more idiomatically like this,

settings.filterNotNull().forEach {} //It also create extra memory.

Or you can use create your own idiomatic foreach extension function filtering null values, without creating extra space

fun <T> Iterable<T?>.forEachNonNull(a: (T) -> Unit) {
    for (i in this) {
        if (i != null){
            a.invoke(i)
        }
    }
}

You can use like this.

settings.forEachNonNull {
}
  • Related