Does using braces inside a Java method reduce performance?

☆樱花仙子☆ 提交于 2019-12-11 13:11:04

问题


It seems as though double-brace initialization increases overhead.

Does using braces inside of a method also reduce performance?

eg.

public class DoIReducePerformanceToo {

    public void aMethod() {

        {
           // Is it a bad idea to use these?
        }

    }

}

I've taken a look at Java's grammar and it seems that this is classified as a block:

Block: 
    { BlockStatements }

BlockStatements: 
    { BlockStatement }

BlockStatement:
    LocalVariableDeclarationStatement
    ClassOrInterfaceDeclaration
    [Identifier :] Statement

but I'm not sure where in the grammar double-brace initialization falls.

My question: does using block statements in methods reduce performance in Java? And are these blocks of the same nature as double-brace initialization?

EDIT:

Inner class instantation is:

ClassCreatorRest: Arguments [ClassBody]

ClassBody: 
    { { ClassBodyDeclaration } }

回答1:


The double-brace initialization trick has nothing to do with normal scopes.

Instead, it creates an anonymous class that inherits the type your initializing, and runs your code in an initialization block (which is syntactic sugar for a constructor).

This extra class has overhead.




回答2:


The block syntax is a part of the grammar, but also changes things such as variable scope. However, after compilation, variables, syntax, scope, and all is just converted into a plain bytecode format. The bytecode does not care about scoping rules, and the like, so there should be no overhead to using extra blocks in your code.

For example, the code

void something()
{
    int x = 5;
    randomStuffWithInt(x);
    {
        int x = 10;
        somethingWithInt(x);
    }
}

could be converted (alpha conversion) to

void something()
{
    int x = 5;
    randomStuffWithInt(x);
    int y = 10;
    somethingWithInt(y);
}

At runtime, it should be exactly the same speed.




回答3:


Late answer, but... I believe there will actually be an execution impact (though not necessarily a large one) given that the run-time engine will create a local variable symbol table on the stack to house variables within the block. If this is done in a looping context or in code otherwise requiring high speed, it may be advisable to avoid its usage.



来源:https://stackoverflow.com/questions/17558977/does-using-braces-inside-a-java-method-reduce-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!