so I just saw this code at work, and the author told me it's for inline optimization.
Class Test{
...
void init(){
//sets variables, call functions, etc
}
...
}
then he calls it in main like this
Test t=new Test();
t.init();
Instead of having a default constructor with the code from init() in it. He told me it's for inline optimization. Is this correct? How is it faster? where do I read up about this?
In computing, inline expansion, or inlining, is a compiler optimization that replaces a function call site with the body of the callee. This optimization may improve time and space usage at runtime, at the possible cost of increasing the size of the final program.
No, Java does not provide inline functions it is typically done by the JVM at execution time.
To answer your question: the Java compiler does not inline methods. The JVM, on the other hand, analyzes your code and will inline at runtime if necessary. Basically, you shouldn't worry about it -- leave it to the JVM, and it will inline if it finds it beneficial.
An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.
It's not faster. It seems to be predicated on the assumption that a method can be inlined but a constructor can't. Unfortunately that's nonsense, so the entire point of it goes out the window.
Even if this were faster, it would almost certainly be a bad idea. Code should not be optimised at the expense of readability, except in extreme circumstances where every last CPU cycle is critical, and in that case you're unlikely to be using Java.
In fact, this is worse than just being harder to read. The next refactoring will inevitably be for the Test
constructor to call the init()
method, so that it doesn't always have to be done manually (and doing it manually is a pain and a potential source of bugs if it gets forgotten); and it is bad practice if a constructor calls a method that can be overridden, because a subclass might inadvertently change what happens at construction time when the superclass constructor is called (see this question for more details). When this happens, a subclass of Test
within the same package will be able to override the init()
method, and then when the subclass invokes super()
, either implicitly or explicitly, the superclass's constructor will end up calling the overridden init()
. (This particular problem could be got rid of by declaring init()
to be private
.)
Don't do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With