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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 aList<Int>
, then+=
will copy the whole list and have terrible performance. but if the list is declared as aMutableList<Int>
, or left not explicitly declared when assigning toArrayList<Int>
(as in your example), then+=
will use theadd()
method directly and be performant.