I have a main loop on my Java game server. I am wondering if converting local variables to global variables will help performance. Running this sample scenario (ii < 100) shows the opposite.
- averageMethodRunTimeHashtable: {localVariableMethod=628, globalVariableMethod=888}
- averageMethodRunTimeHashtable: {localVariableMethod=601, globalVariableMethod=899}
- averageMethodRunTimeHashtable: {localVariableMethod=543, globalVariableMethod=773}
- averageMethodRunTimeHashtable: {localVariableMethod=513, globalVariableMethod=800}
Running (ii < 1000000) or for longer shows inconsistent results. Any suggestions/insight here?
import java.util.Hashtable;
class HelloWorld {
static Hashtable<String, Long> averageMethodRunTimeHashtable = new Hashtable<>();
static long topTime = 0l;
public static void main(String[] args) {
//boolean stopServer = false; //usually stopped by an external source
//while (!stopServer){ //normally this runs "forever"
for (int ii = 0; ii < 100; ii++){ //for this example just run 100 times
topTime = System.nanoTime();
localVariableMethod();
averageMethodRunTime("localVariableMethod", (System.nanoTime() - topTime));
topTime = System.nanoTime();
globalVariableMethod();
averageMethodRunTime("globalVariableMethod", (System.nanoTime() - topTime));
}
System.out.println("averageMethodRunTimeHashtable: " + averageMethodRunTimeHashtable);
}
public static void localVariableMethod(){
for (int i = 0; i < 100; i++){
int test = i;
}
}
static int test_globalVariableMethod = 0;
public static void globalVariableMethod(){
for (int i = 0; i < 100; i++){
test_globalVariableMethod = i;
}
}
public static void averageMethodRunTime(String method, long time) {
if (averageMethodRunTimeHashtable.containsKey(method)) {
averageMethodRunTimeHashtable.put(method, (time + averageMethodRunTimeHashtable.get(method)) / 2);
} else {
averageMethodRunTimeHashtable.put(method, time);
}
}
}
I am trying to answer this part of your question:
There is always some subjectivity in matters of performance based on the context, machine, the way we write the code, etc. And also how we measure it! The measurement itself may add its own overhead.
Jotting down what I feel are by and large true regarding the matter. And based on the below, more often than not, going for local variables more likely to help performance more than long-lived ones (global).
Maps (this contributes to the performance issue)When to go for long-lived variables