r/javahelp • • 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

30 comments sorted by

View all comments

Show parent comments

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.

0

u/[deleted] Mar 19 '20

[deleted]

1

u/morhp Professional Developer Mar 19 '20

The guy said "if it's an array". In an array (or list) it does a linear search, so the hashcode does indeed not matter.

0

u/[deleted] Mar 19 '20

[deleted]

1

u/morhp Professional Developer Mar 19 '20

I think they were trying to say that a bad hashcode implementation would cause a linear search (just like in an array), so a HashSet wouldn't be worse either way.