Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any performance risk to Collections.unmodifiableList?

Tags:

I suggested returning Collections.unmodifiableList() instead of directly returning a member variable, and my colleague is concerned that there would be a performance hit. Of course the best answer is to measure it, and we may do that - but I'd like to know your experiences and any references, pro or con.

like image 990
Carl Manaster Avatar asked Jul 07 '11 00:07

Carl Manaster


People also ask

What is unmodifiable collection in java?

An unmodifiable collection is often a copy of a modifiable collection which guarantees that the collection itself cannot be altered. Attempts to modify it will result in an UnsupportedOperationException exception. It is important to notice that objects which are present inside the collection can still be altered.

What is an unmodifiable Set?

Convenience static factory methods on the List, Set, and Map interfaces let you easily create unmodifiable lists, sets, and maps. A collection is considered unmodifiable if elements cannot be added, removed, or replaced.


1 Answers

No. At least, the OpenJDK implementation literally "replaces" the modification methods with UnsupportedOperationExceptions, the rest adds one level of indirection, which should just get optimized away by the compiler VM (and even so, one level of indirection wouldn't be costly).

If you wish to return a list that cannot be modified, any performance impact would pale in comparison to the loss in correctness, I wouldn't avoid it for performance alone, and I certainly wouldn't avoid it if it's what you need.

like image 91
Mark Elliot Avatar answered Sep 29 '22 11:09

Mark Elliot