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?
You need to distinguish between two things here:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With