我正在做一个项目,从int到String的所有转换都是这样完成的:
int i = 5;
String strI = "" + i;
我不熟悉Java。
这是惯例吗,还是像我猜想的那样,出了什么问题?
我正在做一个项目,从int到String的所有转换都是这样完成的:
int i = 5;
String strI = "" + i;
我不熟悉Java。
这是惯例吗,还是像我猜想的那样,出了什么问题?
当前回答
这取决于你想如何使用你的String。这可以帮助:
String total = Integer.toString(123) + Double.toString(456.789);
其他回答
Mostly ditto on SimonJ. I really dislike the ""+i idiom. If you say String.valueOf(i), Java converts the integer to a string and returns the result. If you say ""+i, Java creates a StringBuilder object, appends an empty string to it, converts the integer to a string, appends this to the StringBuilder, then converts the StringBuilder to a String. That's a lot of extra steps. I suppose if you do it once in a big program, it's no big deal. But if you're doing this all the time, you're making the computer do a bunch of extra work and creating all these extra objects that then have to be cleaned up. I don't want to get fanatic about micro-optimization, but I don't want to be pointlessly wasteful either.
正如已经指出的,Integer.toString()或String.valueOf()是正确的方法。我很好奇,做了一个快速的基准测试:
Integer.toString(i)和String.valueOf(i)在性能上基本相同,Integer.toString(i)稍微快一点。但是i + ""要慢1.7倍。
import java.util.Random;
public class Test {
public static void main(String[] args) {
long concat = 0;
long valueOf = 0;
long toString = 0;
int iterations = 10000;
int runs = 1000;
for(int i = 0; i < runs; i++) {
concat += concat(iterations);
valueOf += valueOf(iterations);
toString += to_String(iterations);
}
System.out.println("concat: " + concat/runs);
System.out.println("valueOf: " + valueOf/runs);
System.out.println("toString: " + toString/runs);
}
public static long concat(int iterations) {
Random r = new Random(0);
long start = System.nanoTime();
for(int i = 0; i < iterations; i++) {
String s = r.nextInt() + "";
}
return System.nanoTime() - start;
}
public static long valueOf(int iterations) {
Random r = new Random(0);
long start = System.nanoTime();
for(int i = 0; i < iterations; i++) {
String s = String.valueOf(r.nextInt());
}
return System.nanoTime() - start;
}
public static long to_String(int iterations) {
Random r = new Random(0);
long start = System.nanoTime();
for(int i = 0; i < iterations; i++) {
String s = Integer.toString(r.nextInt());
}
return System.nanoTime() - start;
}
}
输出:
concat: 1004109
valueOf: 590978
toString: 587236
这取决于你想如何使用你的String。这可以帮助:
String total = Integer.toString(123) + Double.toString(456.789);
使用Integer.toString (tmpInt) .trim ();
这是可以接受的,但我从来没有写过这样的东西。我更喜欢这样:
String strI = Integer.toString(i);