Effective use of Collections.unmodifiable*()

What is more preferable way to expose read-only views of collections when considering efficiency, code readability and other criteria? Does it make any real difference from efficiency point of view to use methodA instead of methodB ? Please consider the situation where list might be accessed quite often - like in the data model of gui table.

I assume that Collectionss.umodifiebleList() creates always a new objects, is this correct?

class A{
    List<Object> list = new ArrayList<Object>();
    List<Object> listReadOnly = Collections.unmodifiableList(list);

    List<Object> methodA(){
        return listReadOnly;
    }

    List<Object> methodB(){
        return Collections.unmodifiableList(list);
    }
}
Jon Skeet
people
quotationmark

Yes, Collections.unmodifiableList does create a new object each time - but it's a pretty cheap operation. (It doesn't have much work to do.)

I'm not sure that the data model of a GUI is likely to fetch the collection over and over again - it will obviously fetch the collection and then iterate over it, but that's a different matter.

If it's only fetching a collection each time something prompts the GUI that the data has changed, that's going to be happening relatively rarely, I'd expect - not in the "hundreds of thousands of times per second" range where this would really be a bottleneck. I'd expect that whatever code is calling this would probably be doing significantly more work than is involved just in creating the unmodifiable list.

Basically, this feels like a micro-optimization too far, unless you've got evidence that it's causing a problem. As always, you should:

  • Define performance requirements
  • Write the code in the simplest possible way which meets other requirements
  • Write tests to check whether or not you've met your performance requirements
  • If you don't currently meet those requirements, carefully work out where the bottlenecks are (whether with a profiler or other techniques)
  • Fix those bottlenecks with as small a loss of readability as possible
  • Lather, rinse, repeat

people

See more on this question at Stackoverflow