Pergunta

My assumption is that, with compiler optimization (e.g., inlining), it makes practically no difference whether a method is "nested" a few levels. Would that be the case indeed?

For example, say that the following 3 classes are declared:

public class Third extends Second
{
    public int test3() // Call test2() and nothing else
    {
        return super.test2();
    }
}

public class Second extends First
{
    public int test2()
    {
        return super.test1(); // Call test1() and nothing else
    }
}

public class First
{
    public int test1() // Calculate a result somehow
    {
        int result = 0;
        ...
        return result;
    }
}

Given 3 already instantiated objects third, second and first, is the cost of the following calls practically the same?

third.test3();
third.test2();
third.test1();
second.test2();
second.test1();
first.test1();

Would it make any difference in optimization if the name of the method was the same?

Foi útil?

Solução

Should you worry about method call overhead? Most of the time, no. It's only when you have a method that's called very heavily in a loop that this overhead matters.

Usually, the nanoseconds of time difference mean squat when the work your methods are doing will be the complete bulk of time spent in execution. Further, as you mentioned, the Java HotSpot VM does do inlining of method calls where appropriate. That decision is up the VM however. See this link:

http://java.sun.com/developer/technicalArticles/Networking/HotSpot/inlining.html

There are better things to worry about in software development these days. Ship that app!

Outras dicas

Each nested call is going to take up another position on the call stack. Since you're not doing much else in the methods, that will make up the bulk of the 'cost' of calling your methods so it will make a difference.

A completely unoticable difference to the user, but a difference nevertheless.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top