Can anyone tell me if either of these will perform better than the other compiled under Java 1.6? Assume MyObject is a class with one field called listField that has a getter and setter
Sample #1:
MyObject obj = new MyObject();
List<String> lst = new ArrayList<String>(1);
lst.add("Foo");
obj.setListField(lst);
Sample #2:
MyObject obj = new MyObject();
obj.setListField(new ArrayList<String> (1));
obj.getListField().add("Foo");
My thinking is that the creation of a local instance of ArrayList will create memory overhead, but calling getListField() whenever you want to add to the list isn't as fast as accessing a local version of the list. Maybe if there are several items to be added to the list, Sample #1 is faster but with only a few items Sample #2 is faster? Or will the compiler optimize this so that calling getListField() is equivalent to accessing a local version of the list?