From f1a75508d319d1f77a93548f581a534b8149513c Mon Sep 17 00:00:00 2001 From: Alexander Udalov Date: Wed, 2 Sep 2015 16:14:37 +0300 Subject: [PATCH] Optimize non-generic CollectionToArray.toArray for empty collection --- .../kotlin/jvm/internal/CollectionToArray.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/core/runtime.jvm/src/kotlin/jvm/internal/CollectionToArray.java b/core/runtime.jvm/src/kotlin/jvm/internal/CollectionToArray.java index ff9ab96922b..b4f0b25df9a 100644 --- a/core/runtime.jvm/src/kotlin/jvm/internal/CollectionToArray.java +++ b/core/runtime.jvm/src/kotlin/jvm/internal/CollectionToArray.java @@ -21,14 +21,22 @@ import java.util.Collection; import java.util.Iterator; public class CollectionToArray { - // Implementation copied from AbstractCollection + // Based on the implementation from AbstractCollection + + @SuppressWarnings("SSBasedInspection") + private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; public static Object[] toArray(Collection collection) { - Object[] r = new Object[collection.size()]; + int size = collection.size(); + if (size == 0) return EMPTY_OBJECT_ARRAY; + + Object[] r = new Object[size]; Iterator it = collection.iterator(); - for (int i = 0; i < r.length; i++) { - if (! it.hasNext()) // fewer elements than expected + for (int i = 0; i < size; i++) { + if (!it.hasNext()) { + // fewer elements than expected return Arrays.copyOf(r, i); + } r[i] = it.next(); } return it.hasNext() ? finishToArray(r, it) : r;