Efficiency of temporary variables in Java

java, performance

Solution

Let's look at what it compiles to. I compile

class A {
    private int x;
    public void setX(int x_){x=x_;}
    public int getX(){return x;}
}

class B {
    int y;
    A a;
    public void setY() {
        //Accessing x of A, assume I already have object of A
        if(a.getX() < 0) {
             y = a.getX();
        }
    }
}

class C {
    int y;
    A a;
    public void setY() {
        //Accessing x of A, assume I already have object of A
        int tmpX = a.getX();
        if(tmpX < 0) {
             y = tmpX;
        }
    }
}

And get for B

  public void setY();
    Code:
       0: aload_0       
       1: getfield      #2                  // Field a:LA;
       4: invokevirtual #3                  // Method A.getX:()I
       7: ifge          21
      10: aload_0       
      11: aload_0       
      12: getfield      #2                  // Field a:LA;
      15: invokevirtual #3                  // Method A.getX:()I
      18: putfield      #4                  // Field y:I
      21: return        
}

and for C

  public void setY();
    Code:
       0: aload_0       
       1: getfield      #2                  // Field a:LA;
       4: invokevirtual #3                  // Method A.getX:()I
       7: istore_1      
       8: iload_1       
       9: ifge          17
      12: aload_0       
      13: iload_1       
      14: putfield      #4                  // Field y:I
      17: return        
}

As `C` only calls `getX` once it will be more "efficient" as this is the most expensive thing there. However you really won't notice this. Especially as the HotSpot JVM will "inline" this method call very quickly.

Unless this is the main bit of code being run There's no point optimising this as you will barely notice it.

However, as mentioned elsewhere there are other reasons beyond performance why the `C` approach is preferable. One obvious one is if the result of `getX()` changes inbetween the two calls (in the presence of concurrency).

Problem

I have a class ``` class A { private int x; public void setX(...){...} public int getX(){return x;} } class B { int y; public void setY() { //Accessing x of A, assume I already have object of A if(a.getX() < 0) { y = a.getX(); } } } class C { int y; public void setY() { //Accessing x of A, assume I already have object of A int tmpX = a.getX(); if(tmpX < 0) { y = tmpX; } } } ``` Which one is better way of coding? The way I have accessed `x of A` in class B or in class C?

Original source

Related problems