5

if i have the code

int getA(){
 return a;
}

and then do something like

int b = obj.getA();

instead of

int b = obj.a;

will that mean that the stack will have to be pushed and popped ultimately slowing down my code?

Amber
  • 507,862
  • 82
  • 626
  • 550
alan
  • 59
  • 1
  • 1
    Performance-in-a-vacuum questions are useless. Profile this yourself after determining it's in a performance-sensitive strip in your application. – djechlin Feb 01 '13 at 19:01

3 Answers3

4

The JIT compiler will inline the method.

The code should look like

int b = obj.GetA();
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • That's not correct. A C/C++ compiler will inline this kind of function but in Java you can't because the VM doesn't know if the function will be referenced or not (using AOP, AspectJ, etc). – cletus Apr 06 '10 at 04:43
  • 1
    @cletus The VM interprets all Java bytecode instructions, and hence, is aware of it - even modifications made by byte-code weaving tools like AspectJ – Binil Thomas Apr 06 '10 at 05:09
  • @binil, Michael: How does this work unless the getter is final? What about subclasses that override the getter? – Thilo Apr 06 '10 at 05:57
  • 4
    @cletus, modern JVM's can apparently detect that the method is not overridden in the actual location where it is used and inline it. If this changes, the code in question goes back to interpretation and then potentially optimized again. – Thorbjørn Ravn Andersen Apr 06 '10 at 06:32
3

I have two answers for you:

  1. I don't think that there is a significant performance penalty for using the getter vs accessing the variable directly. I would worry more about how understandable and readable the code is than performance for this sort of decision.
  2. According to OO design principles, which may or may not be important to you, you would normally hide the data and provide the getter method to access it—there is a detailed discussion on the merits of this approach here.
Community
  • 1
  • 1
JonathanJ
  • 171
  • 1
  • 5
1

Theoretically there is some runtime penalty, due to a method call being made. In reality, this has very little effect on the overall performance due to two reasons:

  1. Unless the obj.getA() is taking place inside the inner-most loop of your program, then its effect on the overall performance of your code will be negligible. When performance is an issue you should consider the bottleneck of your code. There's no point in optimizing code that is out not at these hot spots. In order to identify these spots you need to analyze the execution of your code via a profiler.
  2. As @Michael was saying the JVM uses a "Just In Time" compiler/optimizer that inlines code based on actual execution. It performs just this kind of optimizations (see this talk)
Itay Maman
  • 30,277
  • 10
  • 88
  • 118