tags:

views:

68

answers:

3

For example:

I'm creating a CSV file and I have a CsvOptions object which holds several parameters for the CSV file creation.

if (cells.hasNext()) {
    output.write(csvOptions.getDelimiter());
}

The csvOptions is just a simple container object, that kind you are tempted to not use any getters at all. The getter just returns the value from a private field.

Is it worth to cache the return value of a trivial getter, like getDelimiter() in my example, in terms of

  • ... execution speed?
  • ... coding style?
+2  A: 

Caching shouldn't be an option. If it is a container, make it immutable, i.e. make all its fields public final.

Zed
+3  A: 

The JIT should be able to inline all trivial getters at run-time. So this is not really a concern.

Regarding the coding style, I would prefer the direct call -- unless it makes the line where it occurs too long -- when you need the value only once.

David Schmitt
exactly what I was about to write +1 :)
Martin Lazar
+1  A: 

I believe that Martin Fowler's refactoring explicitly commends not doing this

char delimiter = csvOptions.getDelimiter();

// code here to use delimiter

instead he favours using

csvOptions.getDelimiter()

directly. The argument is two-fold. First there should be minimal performance overhead, compiler and JITers can optimise the function call. Second, by using the method we actually make the code easier to refactor in future.

See Fowler's book referenced here

djna
What about in situations where getDelimiter() is synchronized? Can the JIT do any optimisation then?
Adamski
The original question is assuming the class is immuatable, hence the synchronized question does not arise. No, synchronized will have overheads. But, If you need synchronized then the object may be being updated and so there's questions of consistency. It probably is not meaningful to call getX() and getY() separately, they would not be guaratnteed to be consistent. Rather you might call getSnapshot(), and that result you **would** cache.
djna