Optimize snapshot operations to return special collection implementations when result is empty or has single element.

#KT-9990 Fixed
This commit is contained in:
Ilya Gorbunov
2016-02-10 15:48:05 +03:00
parent 0a5db2fea4
commit f35dc47b4e
10 changed files with 237 additions and 42 deletions
+16 -2
View File
@@ -1003,7 +1003,14 @@ public fun <T> Iterable<T>.toHashSet(): HashSet<T> {
* Returns a [List] containing all elements.
*/
public fun <T> Iterable<T>.toList(): List<T> {
return this.toMutableList()
if (this is Collection) {
return when (size) {
0 -> emptyList()
1 -> listOf(if (this is List) get(0) else iterator().next())
else -> this.toMutableList()
}
}
return this.toMutableList().optimizeReadOnlyList()
}
/**
@@ -1026,7 +1033,14 @@ public fun <T> Collection<T>.toMutableList(): MutableList<T> {
* Returns a [Set] of all elements.
*/
public fun <T> Iterable<T>.toSet(): Set<T> {
return toCollection(LinkedHashSet<T>(mapCapacity(collectionSizeOrDefault(12))))
if (this is Collection) {
return when (size) {
0 -> emptySet()
1 -> setOf(if (this is List) this[0] else iterator().next())
else -> toCollection(LinkedHashSet<T>(mapCapacity(size)))
}
}
return toCollection(LinkedHashSet<T>()).optimizeReadOnlySet()
}
/**