Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed optimizing: private and public variables - Java

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

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!

like image 236
Hidde Avatar asked Sep 09 '11 17:09

Hidde


3 Answers

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.

like image 62
corsiKa Avatar answered Sep 22 '22 05:09

corsiKa


The access modifier on the field doesn't make any difference in speed, but invoking the accessor method does.

However, the difference isn't great, and is likely to diminish after repeated invocations due to JIT compiler optimizations. It depends on your situation, but I haven't found a case where performance concerns justified the elimination of an accessor. Let good design principles drive your decisions.

One good design principle that will help performance in this case is to prohibit inheritance unless you know it is needed and have taken steps to support it. In particular, declaring the class to be final (or at least the accessor method) will provide faster method dispatch and might also serve as a hint to the JITC to inline more agressively.

Keeping accessors final also allows the compiler to inline calls to the accessor. If the field is private, calls to the accessor from within the class can be inlined (and in a good design, these are far and away the most common case), while a package accessible field can be inlined throughout the package, etc.

like image 9
erickson Avatar answered Sep 22 '22 05:09

erickson


As far as I know, when you're calling a getter or any function that will just return some value and nothing else, this method will get inlined so there's no difference whatsoever between the method call and the dirrect access of the field.

like image 1
asenovm Avatar answered Sep 22 '22 05:09

asenovm