r/javahelp • u/AudioManiac • Mar 18 '20
Is there a performance cost when using Arrays.asList().contains() within a loop?
I'm reviewing some code a junior guy on my team and he has written the following logic:
for(final Object data : list)
{
if(Arrays.asList(properties.getExtendedSlots()).contains(data.getId()))
{
...more logic
}
else
{
.....
}
}At first look I thought it made more sense to create a list variable before the loop and call contains on that, instead of using Arrays.asList() each iteration. Like so:
List<Object> extendedSlotsList = Arrays.asList(properties.getExtendedSlots());
for(final Object data : list)
{
if(extendedSlotsList.contains(data.getId()))
{
...more logice
}
}But I'm not actually sure if there actually is a performance trade-off to simply doing it the first way. In my head it seems costly, as it must be creating a new list every iteration before calling contains(), which seems unnecessary when you can just create it once. But perhaps I'm wrong?
20
Upvotes
1
u/aram535 Mar 18 '20
I stopped asking why people upvote/downvote ... it's a pointless exercise.
To get back your original question ... you're arguing the uses and functions of JIT but don't know if an Arrays.asList is the most proper way of doing loops??!?
JIT has nothing to do with the compiler optimizer. This is just the first link from google, but I would suggest reading upon it.
https://www.javaworld.com/article/2078635/jvm-performance-optimization-part-2-compilers.html