float a= 125F; 那么String s = ""; s = String.valueOf(a); 和 String s = ""; s = a + ""; 哪个效率更高呢?今天做个测试和查看各种文章,好像有点头绪。循环n次方的时候,得出时间:
上代码:
public class Test0107 {
@Test
public void test() {
float a = 123F;
String s = "";
int loopCount = 2000_0000;
long start = System.currentTimeMillis();
for (int i = 0; i < loopCount; i++) {
s = String.valueOf(a);
s = String.valueOf(a);
}
long end = System.currentTimeMillis();
System.out.println("String.valueOf:" +(end - start));
long start1 = System.currentTimeMillis();
for (int i = 0; i < loopCount; i++) {
s = a + "";
s = a + "";
}
long end1 = System.currentTimeMillis();
System.out.println("s = a + '' :" +(end1 - start1));
}
}
运行结果:答案是String.valueOf(float)更快。
关于效率:
原因参考贴吧链接:https://bbs.youkuaiyun.com/topics/390837088