Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[K/JS] KT-68860 Optimize listOf(element) #5401

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

lppedd
Copy link

@lppedd lppedd commented Feb 5, 2025

See https://youtrack.jetbrains.com/issue/KT-68860

Note that the better approach (I was unsure if I could do it) would be to make arrayListOf(vararg) and mutableListOf(vararg) expect functions, so that on the JS actual side we can leverage the fact we can pass in an Array<T> to the constructor. That optimization would cover a much wider range of usages. This could be done afterwards tho.

@JSMonk

Previously, calling listOf(T) resulted in the following chain:
1. listOf(T)
2. arrayListOf(vararg T) > new Array
3. A check for 0 elements, always false
4. New ArrayAsCollection
5. New ArrayList(collection)
6. The conversion of ArrayAsCollection to typed array

^KT-68860 Fixed
@fzhinkin
Copy link
Contributor

fzhinkin commented Feb 5, 2025

Does the change actually optimize listOf's performance in any way?

@lppedd
Copy link
Author

lppedd commented Feb 5, 2025

@fzhinkin with the following kotlinx-benchmark class

@State(Scope.Benchmark)
class ListOfBenchmark {
    val element = "abc"

    @Benchmark
    fun arrayListOfBenchmark(bh: Blackhole) {
        val l = arrayListOf(element)
        bh.consume(l)
    }

    @Benchmark
    fun arrayListBenchmark(bh: Blackhole) {
        val a = ArrayList<String>(arrayOf(element))
        bh.consume(a)
    }
}

I see

Benchmark                              Mode  Cnt         Score         Error    Units
ListOfBenchmark.arrayListBenchmark    thrpt    5  43439677.834 ± 2379846.100  ops/sec
ListOfBenchmark.arrayListOfBenchmark  thrpt    5  25355418.456 ±  923573.170  ops/sec

A straightforward ArrayList(array) call seems to win consistently on my machine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants