Jan Idar Hoversholm Jan Idar Hoversholm - 2 months ago 10
Java Question

Performance & Learning differences between ArrayList constructors

Are there any actual performance or bad/good practice differences between the following?

List<String> l = new ArrayList<String>()
{{
add( "ohai" );
add( "Hey;)" );
add( "Hii" );
}};
// or..
List<String> l = new ArrayList<String> ( Arrays.asList( "ohai" , "Hey;)" , "Hii" ) );
// or..
List<String> l = new ArrayList<String>()
{{
addAll( Arrays.asList( "ohai" , "Hey;)" , "Hii" );
}};
// or finally..
List<String> l = Arrays.asList( "ohai" , "Hey;)" , "Hii" );

Answer

The double brace initialization versions will be similar speed, and will also be the slowest. This is because it creates an anonymous class to run the inner block during initialization. Double brace initialization can be syntactically nice, and if you only need to create the List once, the performance decrease is negligible. If you're creating hundreds of lists you might want to choose a different method.

Using addAll vs add you will probably not see a performance difference.

Writing new ArrayList<String>(Arrays.asList(...)) creates a copy of the list returned by Arrays.asList, which will be slower than just calling Arrays.asList.

Wrapping the list in an ArrayList is good idea depending on the operations being performed. For example; ArrayList very good for doing index based lookups.

Comments