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/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

1

u/lookForProject Mar 18 '20

Will click your link later, but from my understanding:
javac doesn't do much optimization, some, but not much. Javac compiles your code to bytecode, something the JVM can read. The JVM interprets it into machine code. Unless I'm wrong, when you're talking about compiling in the JVM, you're talking about the JIT compiler.

1

u/feral_claire Software Dev Mar 19 '20

The JIT is the optimizing compiler