1

In the below scenario, all 3 getXxxxx() methods simple return a property of that class with no additional processing.

Is it more efficient for me to assign them to a temporary variable like I've done with workLimit, or should I just use the getter like I did with getCurrentWork()?

    int x = 0;
    int workLimit = entity.getCurrentWorkLimit();
    JobSet jobSet;
    JobSetQueue queue = workflowProcess.getQueue();
    while (x < workLimit && (jobSet = queue.poll()) != null) {
        getCurrentWork().addLast(jobSet);
    }
Ben
  • 60,438
  • 111
  • 314
  • 488
  • 6
    I doubt very much that it makes any real difference, but the best way to find out is to do a simple test (time it). – Jim W May 23 '13 at 19:37
  • Efficient in what aspect ? – gkalpak May 23 '13 at 19:37
  • If possible, the JVM will inline it anyway. – TC1 May 23 '13 at 19:39
  • This isn't where you're losing performance. Besides, getters are prime candidates for JIT inlining. If this one isn't, the difference will be equivalent to statistical noise. – millimoose May 23 '13 at 19:39
  • Stop micro-optimizing. Rather than trying to shave that 0.1% off of the run-time, rather focus on finding that inefficiency that's slowing your program down by 60%. – Bernhard Barker May 23 '13 at 20:01

3 Answers3

3

The VM optimizes access to simple getters itself - but in fact you usually shouldn't care about it. Therefore, I would usually optimize code for readibility / maintainability instead of performance. Performance optimizations should be based on facts, not assumptions.

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
1

Assuming getCurrentWork() is just returning a variable itself, then the performance will be the same. I think that having the extra variable sometimes makes the code easier to read/scan especially when you have lots of them. In thise case, I'd probably just use the getter.

Dave
  • 13,518
  • 7
  • 42
  • 51
0

You are in essence buying one less stack operation, this is a micro-optimization and as such is almost completely useless, unless you are writing a real-time system.

At the end of the day, profile profile profile

Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
  • I would bet that, even on the realest (?) of real-time system, it still won't make a big enough difference to prefer one over the other. – Bernhard Barker May 23 '13 at 20:04