vigna / fastutil

fastutil extends the Java™ Collections Framework by providing type-specific maps, sets, lists and queues.
Apache License 2.0
1.74k stars 194 forks source link

Optimize toIntArray and friends for empty array #275

Closed amaembo closed 1 year ago

amaembo commented 2 years ago

In some scenarios fastutil collections could often be empty. In this case, it's desired to optimize toIntArray(), etc. to avoid allocation of a new array and iterator instantiation. These allocations are visible in our profiles. We can fix this on our side but I think it worth fixing in the library. Something like:

diff --git a/drv/AbstractCollection.drv b/drv/AbstractCollection.drv
--- a/drv/AbstractCollection.drv    (revision b813824933114ab4cad799fb82784e553fdaec18)
+++ b/drv/AbstractCollection.drv    (date 1654353419404)
@@ -112,6 +112,9 @@
    public KEY_TYPE[] toArray(KEY_TYPE a[]) {
        final int size = size();
        if (a == null) {
+           if (size == 0) {
+               return ARRAYS.EMPTY_ARRAY;
+           }
            a = new KEY_TYPE[size];
        } else if (a.length < size) {
            a = java.util.Arrays.copyOf(a, size);
Index: drv/AbstractList.drv
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/drv/AbstractList.drv b/drv/AbstractList.drv
--- a/drv/AbstractList.drv  (revision b813824933114ab4cad799fb82784e553fdaec18)
+++ b/drv/AbstractList.drv  (date 1654353419417)
@@ -484,6 +484,9 @@
    @Override
    public KEY_TYPE[] TO_KEY_ARRAY() {
        final int size = size();
+       if (size == 0) {
+           return ARRAYS.EMPTY_ARRAY;
+       }
        KEY_TYPE[] ret = new KEY_TYPE[size];
        getElements(0, ret, 0, size);
        return ret;

Sorry I'm new to this project and have no idea how to build it on my Windows machine, so I cannot test whether this works.

vigna commented 1 year ago

So... you're totally right. I'm puzzled as to why the JDK doesn't do this. Maybe they think it's a very rare occurrence.

vigna commented 1 year ago

I have just committed a fix that implements this idea. If you can build and try it out that would be great. I still have to write the unit tests tho (but the modifications are very simple).