我曾尝试在 web/stackoverflow 上搜索此内容,但找不到答案。我不确定是因为它是如此明显还是如此微不足道的差异。
我的基本问题是......哪个性能更好/多少?
String attacker = pairs.getKey();
mobInstanceMap.replace(attacker, 0);
与:
mobInstanceMap.replace(pairs.getKey(), 0);
我喜欢第一个可读性,但我一直在开发一个 MMORPG,我需要非常小心性能。我试着在下面做一个实验,但我想我会问大师,因为我很难推断。我翻转了哪个运行,因为我发现在同时运行两个(一个接一个)时,第二个运行得更好(可能是由于 JVM 优化)。
抱歉,如果这已被询问和回答......或者很明显,但我搜索并没有找到任何东西(也许我不知道要搜索什么)。我不仅想知道“保存”字符串,还想知道其他变量。
public static void main(String[] args){
long hardcodeTotal = 0;
long saveTotal = 0;
// for (int i = 0; i < 10000; i++){
// saveTotal += checkRunTimeSaveString();
// }
for (int i = 0; i < 10000; i++){
hardcodeTotal += checkRunTimeHardcodeString();
}
System.out.println("hardcodeTotal: " + hardcodeTotal/100.0 + "\t" + "saveTotal: " + saveTotal/100.0);
}
private static long checkRunTimeSaveString(){
long StartTime = System.nanoTime();
Iterator<Entry<String, Integer>> it = mobInstanceMap.entrySet().iterator();
while (it.hasNext()) { //to update the AttackingMap when entity(attackee) moves
Entry<String, Integer> pairs = it.next();
String attacker = pairs.getKey();
mobInstanceMap.replace(attacker, 0);
}
return(System.nanoTime() - StartTime);
}
private static long checkRunTimeHardcodeString(){
long StartTime = System.nanoTime();
Iterator<Entry<String, Integer>> it = mobInstanceMap.entrySet().iterator();
while (it.hasNext()) { //to update the AttackingMap when entity(attackee) moves
Entry<String, Integer> pairs = it.next();
mobInstanceMap.replace(pairs.getKey(), 0);
}
return(System.nanoTime() - StartTime);
}