int类型转String类型有下面几种方式:
String var = num + "";
Strng var = String.valueOf(num);
String var = Integer.toString(num);
这三种方法在实际使用过程中都是没有问题的
但是效率上还是有些许区别的
所以写个段代码来对照一下他们的效率
int num = 123456789; long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++){ String var = num + ""; } long end = System.currentTimeMillis(); System.out.println("a + '' 时长为:" + (end - start)); start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++){ String var = String.valueOf(num); } end = System.currentTimeMillis(); System.out.println("String.valueOf(a) 时长为:" + (end - start)); start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++){ String n = Integer.toString(num); } end = System.currentTimeMillis(); System.out.println("Integer.toString(a) 时长为:" + (end - start));
得出结果:
num + '' 时长为:21
String.valueOf(num) 时长为:6
Integer.toString(num) 时长为:5
num + "",在我理解为:String追加,这样会比较耗费时长,新建了2个对象
String.valueOf(num)在底层调用的是Integer.toString(num)
Integer.toString(num)为封装类转换
String.valueOf(a)
->
Integer.toString(a)
->
IntegralToString.intToString(a)
->
convertInt(null, a)
Integer.toString(a)
->
IntegralToString.intToString(a)
->
convertInt(null, a)
因此推荐封装类转换
同理可得,其他类型转换也是同样道理