Skip to content

Instantly share code, notes, and snippets.

@CDRussell
Last active March 4, 2019 03:29
Show Gist options
  • Save CDRussell/fd8d36b498cd97258cff89969d6b2fb5 to your computer and use it in GitHub Desktop.
Save CDRussell/fd8d36b498cd97258cff89969d6b2fb5 to your computer and use it in GitHub Desktop.
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")
@CDRussell
Copy link
Author

CDRussell commented Mar 4, 2019

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