在Java方法中使用花括号是否会降低性能? [英] Does using braces inside a Java method reduce performance?

查看:78
本文介绍了在Java方法中使用花括号是否会降低性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

双括号初始化会增加开销.

>

在方法内部使用花括号是否还会降低性能?

例如

public class DoIReducePerformanceToo {

    public void aMethod() {

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

    }

}

我看过Java的语法,并且似乎被归为一个块:

Block: 
    { BlockStatements }

BlockStatements: 
    { BlockStatement }

BlockStatement:
    LocalVariableDeclarationStatement
    ClassOrInterfaceDeclaration
    [Identifier :] Statement

但是我不确定双括号初始化在语法中的什么位置.

我的问题:在方法中使用块语句是否会降低Java的性能?这些块与双括号初始化具有相同的性质吗?

内部类实例为:

ClassCreatorRest: Arguments [ClassBody]

ClassBody: 
    { { ClassBodyDeclaration } }

解决方案

双括号初始化技巧与正常作用域无关.

相反,它将创建一个匿名类,该类继承您的初始化类型,并在初始化块(这是构造函数的语法糖)中运行您的代码.

这个额外的类有额外的开销.

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 } }

解决方案

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.

这篇关于在Java方法中使用花括号是否会降低性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆