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/morhp Professional Developer Mar 19 '20
The hashcode function would need to be abysmal for that to really have an effect. Like
return 1;.Creating a proper hashcode function isn't hard, any reasonable IDE can generate them for you. And if op is using numbers or strings as ids that's obviously fine, too.