Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does java take time to call a method?

I was doing some experiments in java, and I've encountered a thing that is bugging me. I have realized that in java, when I use a method instead of direct code, it takes more time to process it.

I have the following code:

public static void main(String[] args) {
    long nanoSeconds = System.nanoTime();
    int i = foo();
    System.out.println(i);
    System.out.println("Elapsed Nanoseconds = " + (System.nanoTime() - nanoSeconds));
    nanoSeconds = System.nanoTime();
    int l = 10;
    i = l;
    System.out.println(i);
    System.out.println("Elapsed Nanoseconds = " + (System.nanoTime() - nanoSeconds));
}

public final static int foo() {
    int i = 10;
    return i;
}

It is a simple code divided in two parts. The first one measures the time of foo() and shows the returned value of foo(), and the second part does the same but without calling foo().

The result was the following:

10

Elapsed Nanoseconds = 601582

10

Elapsed Nanoseconds = 49343

So my question is if is there a way to not loose this performance?

Thanks all.

like image 349
Alvaro Lemos Avatar asked Dec 02 '14 11:12

Alvaro Lemos


1 Answers

You will not obtain any meaningful benchmark this way.

You don't account for the JIT.

The compiler will not perform any optimization in this regard, apart from very obvious ones; when it sees a method call in the source code, even if this method call always returns the same value, it will generate bytecode which invokes the method; when it sees a constant, it will generate an ldc (load constant) bytecode instruction.

BUT.

Then the JIT kicks in at some point. If it determines that a method call always returns the same result, then it will inline the call. At runtime. But this is only done after a certain amount of executions of that code are performed, and it always has a way back if it admits that it has missed at some point (this is backtracking).

And that is but one optimization a good JIT implementation can perform.

You want to watch this video. Long story short: with Oracle's JVM, optimization will start to kick in only after a piece of code will be executed 10000 times at least — for some definition of "piece of code".

like image 71
fge Avatar answered Sep 20 '22 15:09

fge