How do I convert from int to String?

后端 未结 20 2759
不思量自难忘°
不思量自难忘° 2020-11-21 23:40

I\'m working on a project where all conversions from int to String are done like this:

int i = 5;
String strI = \"\" + i;
         


        
20条回答
  •  悲哀的现实
    2020-11-22 00:00

    As already pointed out Integer.toString() or String.valueOf() are the way to go. I was curious and did a quick benchmark:

    Integer.toString(i) and String.valueOf(i) are basically identical in performance, with Integer.toString(i) being a tiny bit faster. However i + "" is 1.7 times slower.

    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;
        }
    }
    

    Output:

    concat: 1004109
    valueOf: 590978
    toString: 587236
    

提交回复
热议问题