我想知道创建重复代码以避免变量在CPU上是否更有效,如果是,是否值得重复代码,如下例所示?
我目前有以下内容:
c.set("arenas."+name+".team"+team+".world", loc.getWorld().getName());
c.set("arenas."+name+".team"+team+".x", loc.getX());
c.set("arenas."+name+".team"+team+".y", loc.getY());
c.set("arenas."+name+".team"+team+".z", loc.getZ());
c.set("arenas."+name+".team"+team+".pitch", loc.getPitch());
c.set("arenas."+name+".team"+team+".yaw", loc.getYaw());3
以下内容在CPU上会更快。它与上面的代码完全相同:
if(team == 1) {
c.set("arenas."+name+".team1.world", loc.getWorld().getName());
c.set("arenas."+name+".team1.x", loc.getX());
c.set("arenas."+name+".team1.y", loc.getY());
c.set("arenas."+name+".team1.z", loc.getZ());
c.set("arenas."+name+".team1.pitch", loc.getPitch());
c.set("arenas."+name+".team1.yaw", loc.getYaw());
}else {
c.set("arenas."+name+".team2.world", loc.getWorld().getName());
c.set("arenas."+name+".team2.x", loc.getX());
c.set("arenas."+name+".team2.y", loc.getY());
c.set("arenas."+name+".team2.z", loc.getZ());
c.set("arenas."+name+".team2.pitch", loc.getPitch());
c.set("arenas."+name+".team2.yaw", loc.getYaw());
}
在第二个例子中,if-else语句是否比第一个例子中连接六个字符串快?
我知道这会占用更多磁盘空间,但是它会节省处理能力吗?值得吗?
编辑:我进行了一项测试,每次测试都有100,000,000次试验。示例1花了11.112秒,示例2花了9.479秒。示例2快了1.633秒。这值得么?如果CPU和磁盘空间很重要,我会使用示例1吗?答案 0 :(得分:3)
优先考虑微优化的可读性(事实上,您目前的方法可能比您提出的替代方案更有效,因为分支相对昂贵 - 但不进行微观优化)。我将提取一种方法来构建密钥(同样,最大化可读性)。像,
private static String buildKey(String name, int team, String key) {
return String.format("arenas.%s.team%d.%s", name, team, key);
}
然后你可以调用它,
c.set(buildKey(name, team, "world"), loc.getWorld().getName());
c.set(buildKey(name, team, "x"), loc.getX());
c.set(buildKey(name, team, "y"), loc.getY());
c.set(buildKey(name, team, "z"), loc.getZ());
c.set(buildKey(name, team, "pitch"), loc.getPitch());
c.set(buildKey(name, team, "yaw"), loc.getYaw());