ps-aux
ps-aux

Reputation: 12146

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);
    }
}

Upvotes: 2

Views: 168

Answers (2)

Bohemian
Bohemian

Reputation: 425053

Don't do methodA, because you must maintain state between the lists, which can be tricky in multi-threaded environments, and is a pain even if for a single-threaded environment.

Do methodB, and let the JDK sort out efficiency (it's pretty fast).

Note: Unless the elements in the list are themselves immutable, methodB is not completely safe, because while list might be unmodifiable, its elements may be themselves modified. Consider:

List<Date> list = new ArrayList<Date>();
list.add(new Date());
List<Date> dates = Collections.unmodifiableList(list);
Date date = dates.get(0);
date.setTime(0);  // The date in the original list has now changed!

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500785

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

Upvotes: 10

Related Questions