Would there be any appetite for adding this, as an...
# stdlib
r
Would there be any appetite for adding this, as an optimisation to avoid the allocation of a new ArrayList in the current
Iterable<T>.map
method?
Copy code
public inline fun <T, R> Collection<T>.map(transform: (T) -> R): List<R> {
  return if (this.isEmpty()) emptyList() else (this as Iterable<T>).map(transform)
}
👍 2
👎 1
s
I cannot find it now but I remember reading a blog post from Google where they removed most of such checks from their code. The basic conclusion was that saving a small amount of work on a rare case (such as mapping the empty list) did not improve general performance since you are now adding more work to the frequent case.
👍 2
r
FWIW other bits of the stdlib do have this sort of optimisation:
Copy code
public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean {
    if (this is Collection && isEmpty()) return true
    for (element in this) if (!predicate(element)) return false
    return true
}

public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean {
    if (this is Collection && isEmpty()) return false
    for (element in this) if (predicate(element)) return true
    return false
}
So I guess a more consistent suggestion would be to change
Iterable<T>.map
to this:
Copy code
public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
    return if (this is Collection && isEmpty()) emptyList()
    else mapTo(ArrayList(collectionSizeOrDefault(10)), transform)
}