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

I was wondering about the difference between a class member variable and a method local variable for performance. Here's an explanation:

This is for a class member variable;

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

      

And this is for a local variable of a method;

      public class Foo{

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

      

Suppose I call this function frequently, in the second example, the JVM is created every time the ref (if this is how I should write like the first example?) Or the JVM, create once and always use it?

+3


source to share


2 answers


There are two things to distinguish here:

  • Variables
  • objects

In both cases, a new String

object is created for the expression a + b

.



When you use a class field to store the result, the same memory is used every time. The memory is somewhere on the heap. But: if you call this method from multiple threads at the same time, they will all use the same memory to store their result, and they will overwrite it. This means that one thread can see the result of another thread, which is bad.

When using a local variable, new memory is used for each method call. But this is local memory on the call stack, which costs almost nothing. Alternatively, you can call your method from multiple threads at the same time.

Hence, you should use the second snippet.

+4


source


Class fields

will be accessible from several methods from the class, whereas local variables

only from the method. You would Class fields

only use it if they are indeed an attribute of another class that keeps them local.



+1


source







All Articles