Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, class member or method-local variable: which one is better for performance?

I wondered the difference between class member variable and method-local variable for performance. Here the explaining;

This is for class member variable;

    public class Foo{
      static String ref;
      public static void union(String a, String b){
       ref= a+b;
       }
    }

And this is for method-local variable;

      public class Foo{

      public static void union(String a, String b){
       String ref= a+b;
       }
    }

Suppose I call this function oftenly, in second example does the JVM create every time the ref reference(if so should I write like first example?) or JVM create a once and use it always?

like image 302
PeerNet Avatar asked May 20 '26 15:05

PeerNet


1 Answers

You need to distinguish between two things here:

  • variables
  • objects

In both of your cases, a new String object for the expression a + b is created.

When you use a class field for storing the result, the same memory is used every time. The memory is somewhere in the heap. But: if you call that method from multiple threads at the same time, they will all use the very same memory for storing their result, and they will overwrite it. This means that one thread might see the result of a different thread, which is bad.

When you use a local variable, new memory is used for every method call. But this is local memory on the call stack, which practically doesn’t cost anything. Plus, you can call your method from multiple threads at the same time.

Therefore, you should use the second snippet.

like image 190
Roland Illig Avatar answered May 23 '26 04:05

Roland Illig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!