Skip to content

Commit 3ca5e75

Browse files
committed
KT-75801: Optimize stdlib Array<T>.toList() function
Replace inner `toMutableList()` call with `copyOf().asList()`. This change reduce number of array copies from two to one.
1 parent e9d007a commit 3ca5e75

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

libraries/stdlib/common/src/generated/_Arrays.kt

+1-1
Original file line numberDiff line numberDiff line change
@@ -9831,7 +9831,7 @@ public fun <T> Array<out T>.toList(): List<T> {
98319831
return when (size) {
98329832
0 -> emptyList()
98339833
1 -> listOf(this[0])
9834-
else -> this.toMutableList()
9834+
else -> copyOf().asList()
98359835
}
98369836
}
98379837

libraries/tools/kotlin-stdlib-gen/src/templates/Snapshots.kt

+11-1
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ object Snapshots : TemplateGroupBase() {
173173
return this.toMutableList().optimizeReadOnlyList()
174174
"""
175175
}
176-
body(CharSequences, ArraysOfPrimitives, ArraysOfObjects) {
176+
body(CharSequences, ArraysOfPrimitives) {
177177
"""
178178
return when (${f.code.size}) {
179179
0 -> emptyList()
@@ -182,6 +182,16 @@ object Snapshots : TemplateGroupBase() {
182182
}
183183
"""
184184
}
185+
// For object array, ensure a single array copy instead of delegating to `toMutableList`, which can cause two copies (see KT-75801)
186+
body(ArraysOfObjects) {
187+
"""
188+
return when (${f.code.size}) {
189+
0 -> emptyList()
190+
1 -> listOf(this[0])
191+
else -> copyOf().asList()
192+
}
193+
"""
194+
}
185195
body(Sequences) { optimizedSequenceToCollection("emptyList", "listOf", "ArrayList") }
186196
specialFor(Maps) {
187197
doc { "Returns a [List] containing all key-value pairs." }

0 commit comments

Comments
 (0)