Do not use spread-operator when it causes excessive array copying

This commit is contained in:
Ilya Gorbunov
2017-05-15 21:37:53 +03:00
parent 1eb1735ac9
commit ddf6599b38
2 changed files with 8 additions and 3 deletions

View File

@@ -43,7 +43,7 @@ public fun <K, V> emptyMap(): Map<K, V> = @Suppress("UNCHECKED_CAST") (EmptyMap
*
* @sample samples.collections.Maps.Instantiation.mapFromPairs
*/
public fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> = if (pairs.size > 0) linkedMapOf(*pairs) else emptyMap()
public fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> = if (pairs.size > 0) pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) else emptyMap()
/**
* Returns an empty read-only map.
@@ -123,7 +123,7 @@ public inline fun <K, V> linkedMapOf(): LinkedHashMap<K, V> = LinkedHashMap<K, V
* @sample samples.collections.Maps.Instantiation.linkedMapFromPairs
*/
public fun <K, V> linkedMapOf(vararg pairs: Pair<K, V>): LinkedHashMap<K, V>
= LinkedHashMap<K, V>(mapCapacity(pairs.size)).apply { putAll(pairs) }
= pairs.toMap(LinkedHashMap(mapCapacity(pairs.size)))
/**
* Calculate the initial capacity of a map, based on Guava's com.google.common.collect.Maps approach. This is equivalent

View File

@@ -26,6 +26,10 @@ package kotlin.comparisons
*/
public fun <T> compareValuesBy(a: T, b: T, vararg selectors: (T) -> Comparable<*>?): Int {
require(selectors.size > 0)
return compareValuesByImpl(a, b, selectors)
}
private fun <T> compareValuesByImpl(a: T, b: T, selectors: Array<out (T)->Comparable<*>?>): Int {
for (fn in selectors) {
val v1 = fn(a)
val v2 = fn(b)
@@ -84,8 +88,9 @@ public fun <T : Comparable<*>> compareValues(a: T?, b: T?): Int {
* compare as equal, the result of that comparison is returned from the [Comparator].
*/
public fun <T> compareBy(vararg selectors: (T) -> Comparable<*>?): Comparator<T> {
require(selectors.size > 0)
return object : Comparator<T> {
public override fun compare(a: T, b: T): Int = compareValuesBy(a, b, *selectors)
public override fun compare(a: T, b: T): Int = compareValuesByImpl(a, b, selectors)
}
}