Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java is there a performance difference between referencing a field through getter versus through a variable?

Is there any differences between doing

Field field = something.getSomethingElse().getField();
if (field == 0) {
//do something    
}
somelist.add(field);

versus

if (something.getSomethingElse().getField() == 0) {
//do something    
}
somelist.add(something.getSomethingElse().getField());

Do references to the field through getters incur a performance penalty or is it the same as referencing an assigned variable? I understand that the variable is just a reference to the memory space, so the getter should just be another way to get at that memory space.

Note that this is an academic question (school of just curious) rather then a practical one.

like image 505
James McMahon Avatar asked Jul 28 '09 18:07

James McMahon


1 Answers

It's a negligible detriment. Don't concern yourself with it too much or you'll fall prey to premature optimization. If your application is slow, this isn't the reason why.

like image 140
Spencer Ruport Avatar answered Oct 08 '22 07:10

Spencer Ruport