2

What's best for read-iterating over an IntArrayList from the fastutil library in Java?

fastutil is a library that is used for increased performance above what the standard library's collection classes and algorithms can do. So "best" in this context means best performance.

I've followed the advice in the fastutil docs and set my IDE (Eclipse) to warn when boxing happens: Window -> Preferences -> Java -> Compiler -> Errors/Warnings -> Potential Programming Problems -> Boxing and unboxing conversions -> set to Warning
However, Eclipse seems to omit some warnings. See below in the code for details.

I came across these alternatives so far for iterating:

IntArrayList list = ...;

// 1. for-loop-with-index-variable
for (int i = 0; i < list.size(); i++) {
    // do something with list.getInt(i)
}

// 2. for-each-loop-with-wrapped
Integer value = list.getInt(0); // Eclipse correctly warns in this line
for (Integer element : list) { // autoboxing happens here somewhere, but Eclipse does NOT warn
    // do something with element
}

// 3. for-each-loop-with-primitive
for (int element : list) { // Eclipse does NOT warn. Does autoboxing happen here?
    // do something with element
}

// 4. forEach-method-with-consumer
list.forEach((int element) -> {
    // do something with element
});

// 5. for-loop-with-IntIterator
for (IntIterator iter = list.iterator(); iter.hasNext();) {
    // do something with iter.nextInt()
}
Daniel S.
  • 6,458
  • 4
  • 35
  • 78
  • If you want to write the perfect answer, feel encouraged to also include details about write-iterating over such a list. I will accept the best answer in a few days. – Daniel S. May 17 '20 at 17:06
  • Yes, I can do the benchmarks myself. And I will if nobody else is interested. – Daniel S. May 17 '20 at 17:13
  • From an educated guess, the fastest is very likely #1, followed by #5. #4 could beat #1 and #5 if there is some parallelism involved, which is not guaranteed. #2 and #3 definitely autobox and are the usual losers in this scenario. – Olivier Grégoire May 17 '20 at 17:27

2 Answers2

1

Autoboxing definitely occurs in #2 and #3 cases. I think #1 or #5 would be most optimal in terms of performance.

Taken from the Fastutil documentation https://fastutil.di.unimi.it/docs/index.html:

Note that the “for each” style of iteration can hide boxing and unboxing: even if you iterate using a primitive variable (as in for(long x: s), where s is a LongSet), the actual iterator used will be object-based, as Java knows nothing about fastutil's type-specific next()/previous() methods.

dxiong7
  • 11
  • 3
0

Definitely #1. :)

[And I have to add more character of StackOverflow won't let me post this.]

seba
  • 403
  • 3
  • 12