Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does a Java getter incur a performance penalty

Tags:

java

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?

like image 622
alan Avatar asked Apr 06 '10 04:04

alan


2 Answers

The JIT compiler will inline the method.

The code should look like

int b = obj.GetA();
like image 133
Michael Burr Avatar answered Oct 05 '22 23:10

Michael Burr


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.
like image 39
JonathanJ Avatar answered Oct 06 '22 01:10

JonathanJ