Reputation: 6650
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()
}
Upvotes: 3
Views: 1098
Reputation: 11
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.
Upvotes: 1
Reputation: 403
Definitely #1. :)
[And I have to add more character of StackOverflow won't let me post this.]
Upvotes: 0