速度优化:私有和公共变量 - Java [英] Speed optimizing: private and public variables - Java

查看:208
本文介绍了速度优化:私有和公共变量 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问这个问题纯粹是为了问题的速度方面。

I am asking this question purely for the speed aspects of the question.

在私人或私人物品上获取价值时,速度的差异是什么? public(Java)?

What is the difference in speed between getting the value from an object when it is private or public (Java)?

class MyClass {
    public int myInt = 5;
}
class MyOtherClass {
    private int myInt = 5;

    public int getMyInt() {
        return myInt;
    }
}
class MyMainClass {
    public static void main (String [] args) {
        MyClass myObject = new MyClass();
        MyOtherClass myOtherObject = new MyOtherClass();

        // which is faster?
        System.out.println(myObject.myInt);
        System.out.println(myOtherObject.getMyInt ());
    }
}

我知道我可以测试它,但是如果还有人的话知道了,它不会伤害:)
提前致谢!

I know I can test it, but if anyone alreay knows it, it can't hurt :) Thanks in advance!

推荐答案

公共和私人访问仅此而已在编译时确定您是否可以访问变量。在运行时,它们完全相同。这意味着如果您可以欺骗JVM认为您有权访问(通过反射,不安全或修改字节码),那么您可以。公共和私有只是编译时间信息。这并不是说它不会存储在字节码中,因为它确实如此,但只有在某些东西试图对其进行编译时才能被引用。

Public and private access is nothing more than determining at compile time whether or not you have access to a variable. At run time, they are exactly the same. This means if you can trick the JVM into thinking you have access (through reflection, unsafe, or modifying the bytecode) then you can. Public and private is just compile time information. That's not to say it doesn't get stored in the bytecode, because it does, but only so it can be referenced if something tries to compile against it.

这篇关于速度优化:私有和公共变量 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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