Alex Rivera | Logout

Is there any performance risk to Collections.unmodifiableList?

Asked 2011-07-07T00:20:42.943
24

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.

Edit
Report

1 Answer

6

If you look at the implementation you'll see that Collections.unmodifiable is just a thin wrapper around the real collection that throws an exception for all remove/add methods instead of forwarding it. So no there's no performance hit (the forwarding call will be inlined by the JIT).

So yes you absolutely should return an unmodifiable collection instead of the original most of the times - much better coding practice.

answered 2011-07-07T00:24:38.657

Your Answer