And*_*den 4 java string-concatenation
从字符串,整数和浮点数构建字符串的最高效方法是什么?目前我正在这样做,它使用了大量的CPU时间.
String frame = this.frameTime + ":" +
this.player.vertices[0].x + "," +
this.player.vertices[0].y + "," +
this.player.activeAnimId + "," +
(int)this.player.virtualSpeed + "," +
this.map.getCurrentTime() +
(this.player.frameSound == -1 ? "" : "," + this.player.frameSound) +
(this.player.frameDecal.equals("") ? "" : "," + this.player.frameDecal) +
";";
Run Code Online (Sandbox Code Playgroud)
有没有办法更快地做到这一点?
Jon*_*eet 19
这应该已经很快 - 它将在StringBuilder内部用于连接.可以说StringBuilder明确地使用可以消除空字符串的串联,但它不太可能产生很大的不同.
无论如何,你多久一次这样做?它必须经常发生,因为它是一个瓶颈......你真的需要经常这样做吗?
编辑:对于那些说"使用StringBuilder,它会更快"的人 - 考虑这段代码:
public class Test
{
public static void main(String[] args)
{
int x = 10;
int y = 20;
int z = 30;
String foo = x + "," + y + "," + z + ";";
System.out.println(foo);
}
}
Run Code Online (Sandbox Code Playgroud)
编译它,然后javap -c用来查看编译器生成的内容......