我已尝试在此处搜索web / stackoverflow但无法找到答案。我不确定是不是因为它是如此明显或可忽略不计的差异。
我的基本问题是......哪个表现更好/多少?
String attacker = pairs.getKey();
mobInstanceMap.replace(attacker, 0);
VS
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);
}
答案 0 :(得分:5)
很可能,中间分配将由JVM优化,并且它们将具有完全相同的性能。
在任何一种情况下,这些事情的可能性能命中几乎都不会引起注意。除非在极端情况下,否则您不应担心性能。始终选择可读性。
还应该补充一点,您在上面的代码中使用的微基准测试类型非常难以从中获得可靠的测量结果。您无法控制太多因素(内部JVM优化,JVM预热等),以准确测量您要测试的确切内容。
答案 1 :(得分:1)
您可以使用JVisualVM等工具分析这两种实现,以查看确切的区别。如果您想要以高音量进行测试,可以使用像Contiperf http://databene.org/contiperf之类的工具,然后分享我们所有人的结果:)
答案 2 :(得分:0)
我同意Keppil的观点,表现可能完全相同。如果存在细微差别,并且如果您关心性能如此小的改进,那么您可能不应该首先使用Java。