Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Probability of getters and setters getting inlined by the compiler

My question is pretty straightforward:

Q: What is the chance that a getter / setter method will get inlined by the compiler in Java?
(Obviously there isn't a definite answer to this, but other information would be appreciated)

Extra: I understand there is always a chance the compiler (Standard and JIT) will decide to make a method inline, and when it comes to getters and setters this is usually what the programmer wants.

Thanks in advance.

like image 532
Acidic Avatar asked Dec 26 '11 22:12

Acidic


3 Answers

The compiler (javac) tend to have negligible impact on optimization, as optimization happens at run time.

As of the JIT yes,it will probably inline either sooner or later.depending on how heavily the code is used, so a function call overhead may be seen at first, but when the getter/setter has been called sufficiently often then it is inlined.

like image 64
Shaunak Avatar answered Oct 21 '22 03:10

Shaunak


The compiler may inline when a method is final and the accessed fields are accessible to the caller. Then it's up to the compiler to determine whether the method is "simple" enough for inlining.

In practice, setting or getting a field is generally considered simple enough, so a final accessor for an accessible field will be inlined. Accessors for private fields will be inlined within their declaring class; accessors for protected fields will be inlined throughout the declaring package and any derived classes; &c.

At runtime, the JIT is likely to perform additional inlining based on analysis of running code.

like image 21
erickson Avatar answered Oct 21 '22 03:10

erickson


I imagine about zero (at least in the non-JIT case), since these are Java Bean conventions and they always need to be public, so the compiler cannot predict who might call the methods. You might change the implementation of one of these which would break an inlined caller. There is nothing to require that they need to be implemented only to set a field.

like image 29
Francis Upton IV Avatar answered Oct 21 '22 04:10

Francis Upton IV