Last active
March 4, 2019 03:29
-
-
Save CDRussell/fd8d36b498cd97258cff89969d6b2fb5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val itemsToAdd = 500_000 | |
// val list = mutableListOf<Int>() | |
val tMutableList = measureNanoTime { | |
val list = mutableListOf<Int>() | |
for (i in 1..itemsToAdd) { | |
list += i | |
} | |
} | |
Timber.i("Using += on `MutableList<Int>` took ${TimeUnit.NANOSECONDS.toMillis(tMutableList)}ms") | |
// var list: List<Int> = mutableListOf() | |
val t = measureNanoTime { | |
var list: List<Int> = mutableListOf() | |
for (i in 1..itemsToAdd) { | |
list += i | |
} | |
} | |
Timber.i("Using += on `List<Int>` took ${TimeUnit.NANOSECONDS.toMillis(t)}ms") |
Thanks for the comment.
I've since updated the post to highlight a further nuance: that +=
will have different behaviour depending on how you define the list. If the list is declared as a List<Int>
, then +=
will copy the whole list and have terrible performance. but if the list is declared as a MutableList<Int>
, or left not explicitly declared when assigning to ArrayList<Int>
(as in your example), then +=
will use the add()
method directly and be performant.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
About this:
https://craigrussell.io/2019/03/shooting-yourself-in-the-foot-while-adding-an-element-to-a-kotlin-list/
You actually have missed another type of the meaning for
+=
:val tPlus = measureNanoTime { val list = ArrayList<Int>() for (i in 1..itemsToAdd) { list += i } }
On this case, it's exactly the same as
add()
, because when you click on it, you get this:`
/**
*/
@kotlin.internal.InlineOnly
public inline operator fun MutableCollection.plusAssign(element: T) {
this.add(element)
}
`
And the result, on Pixel 2 with Android P :
Both finished in less than 100ms ( around 60ms, usually)