为什么它不直接使用实例字段,而是将其分配给局部变量? [英] Why it doesn't use the instance field directly, but assigns it to a local variable?

查看:109
本文介绍了为什么它不直接使用实例字段,而是将其分配给局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 java.util.concurrent.ArrayBlockingQueue 的来源,并找到了一些我不理解的代码:

I'm reading the source of java.util.concurrent.ArrayBlockingQueue, and found some code I don't understand:

private final ReentrantLock lock;

public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        if (count == items.length)
            return false;
        else {
            insert(e);
            return true;
        }
    } finally {
        lock.unlock();
    }
}

注意这一行:

final ReentrantLock lock = this.lock;

为什么它不使用 this.lock 直接,但是将它分配给局部变量?

Why it doesn't use this.lock directly, but assigns it to a local variable?

推荐答案

是否可以用于优化目的?

可能更容易将局部变量直接分配给带有JIT编译器的寄存器。

Possibly a local variable could more easily be directly allocated to a register with a JIT compiler.

至少在Android中,对于API的第一个版本,访问本地变量比访问实例变量便宜(不能代表更新的版本)。可能是普通的Java是相同的,在某些情况下使用本地是有意义的。

At least in Android, for the first versions of the API, accessing a local variable was cheaper than accessing an instance variable (can't speak for newer versions). It could be that plain Java is the same, and in some cases it makes sense to use a local.

实际上,找到了主题确认此处。提取:

Actually, found a thread confirming this here. Extract:


这是Doug Lea流行的编码风格。这是一个极端的
优化,可能不是必需的;你可以期望JIT到
进行相同的优化。 (您可以尝试自己检查机器代码
!)尽管如此,复制到本地生成最小的
字节码,而对于低级代码,编写一个接近
的代码是很好的。机器。

It's a coding style made popular by Doug Lea. It's an extreme optimization that probably isn't necessary; you can expect the JIT to make the same optimizations. (you can try to check the machine code yourself!) Nevertheless, copying to locals produces the smallest bytecode, and for low-level code it's nice to write code that's a little closer to the machine.

这篇关于为什么它不直接使用实例字段,而是将其分配给局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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