我的 Java 游戏服务器上有一个主循环。我想知道将局部变量转换为全局变量是否有助于性能。运行此示例场景 (ii < 100) shows the opposite.
跑步 (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);
}
}
}
我正在尝试回答你问题的这一部分:
我想知道将局部变量转换为全局变量是否有助于性能。
基于上下文、机器、我们编写代码的方式等,以及我们如何衡量它,性能问题总是存在一些主观性!测量本身可能会增加其自身的开销。
记下我对此事的看法大体上是正确的。基于以下内容,通常情况下,选择局部变量比长期变量(全局变量)更有可能提高性能。
Map
s (这会导致性能问题)