java - 类(class)阅读领域费用

标签 java performance

Java 7

我正在阅读 J. Bloch 的 effective Java,现在正在阅读有关延迟初始化字段的部分。他介绍了所谓的双重检查惯用法,如下:

public static void main(String[] args){

        Test t = new Test();
        long now = System.nanoTime();
        t.getT();
        long invokationTime = System.nanoTime() - now;
        System.out.println(invokationTime); //Prints 3299 averagely
    }

    private static class Test{
        private volatile Test field;

        public Test getT(){
            Test result = field;  // <----- Note the local variable here
            if(result != null){
                synchronized (this) {
                    result = field;
                    if (result == null)
                        field = result = new Test();
                }
            }
            return result;
        }
    }

DEMO

他对使用局部变量给出了以下解释:

What this variable does is to ensure that field is read only once in the common case where it’s already initialized.

现在,让我们考虑以下代码:

public static void main(String[] args){

    Test t = new Test();
    long now = System.nanoTime();
    t.getT();
    long invokationTime = System.nanoTime() - now;
    System.out.println(invokationTime);  //Prints 3101 averagely
}

private static class Test{
    private volatile Test field;

    public Test getT(){
        if(field != null){
            synchronized (this) {
                if (field == null)
                    field = new Test();
            }
        }
        return field;
    }
}

DEMO

在我的机器上,第二种惰性初始化方法甚至更快。但在 ideone 的机器上,正如 J. Bloch 所说,他们使用了大约 7985 和 10630。那么是否值得使用这样的局部变量来进行优化呢?据我所知,读取和写入变量的成本几乎相等。

因此,只有当该方法主要由此类轻量级操作组成时,我们才应该担心它,对吗?

最佳答案

这是值得的,因为您已经确定急切加载和同步都太昂贵了。但实际上,几乎可以肯定不是。您实际需要双重检查锁定代码的情况往往是在非锁定数据结构和事物中。高性能代码的良好设计往往会将其插入孤立的位置,这样您就不会在每次接触代码时搬起石头砸自己的脚。

关于java - 类(class)阅读领域费用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33951862/

相关文章:

java - 无法让类(class)项目 FTP 服务器发送 226

java - 如何将注释应用于类的每个方法?

java - 是什么导致运行代码中的 java.lang.ClassNotFoundException

r - 在 R 中逐行构建复杂数据帧的有效方法

python - 以下哪项是在 Python 中检查列表是否为空的最快方法?

java - 三元运算符的两个右 watch 达式都必须是兼容类型吗?

java - 正则表达式匹配没有特定顺序的组

ruby - Ruby 自带方法的性能

iphone - glClearColor() 将 iPhone 的渲染利用率推至 27%

Javascript 性能 : Variable vs Large object's attribute