java how expensive is a method call

Would it be more optimal for me to just copy and paste the two lines in my clear() method into the constructor instead of calling the actual method?

The compiler can perform that optimization. And so can the JVM. The terminology used by compiler writer and JVM authors is “inline expansion”.

If so how much of a difference does it make?

Measure it. Often, you’ll find that it makes no difference. And if you believe that this is a performance hotspot, you’re looking in the wrong place; that’s why you’ll need to measure it.

What if my constructor made 10 method calls with each one simply setting an instance variable to a value?

Again, that depends on the generated bytecode and any runtime optimizations performed by the Java Virtual machine. If the compiler/JVM can inline the method calls, it will perform the optimization to avoid the overhead of creating new stack frames at runtime.

What’s the best programming practice?

Avoiding premature optimization. The best practice is to write readable and well-designed code, and then optimize for the performance hotspots in your application.

Leave a Comment