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")
@AndroidDeveloperLB
Copy link

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:
`
/**

  • Adds the specified [element] to this mutable collection.
    */
    @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)

@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