top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Performance wise which string initialization is better one in java

+2 votes
417 views

performance wise which one is better one in java

String s3 = String.valueOf(2);
String s4 = Integer.toString(2);
String s5 = 2+"";
posted Feb 16, 2014 by Prasad

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

I tried the following program

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final int iterCount = 1000000;

        // test String.valueOf
        long start = System.currentTimeMillis(); 
        for (int i = 0; i < iterCount; i++) {
            String s = String.valueOf(i);
        }
        System.out.println("DEBUG: String.valueOf took "
        + (System.currentTimeMillis() - start) + " ms for "
        + iterCount + " iterations");

        // test Integer.toString
        start = System.currentTimeMillis();
        for (int i = 0; i < iterCount; i++) {
            String s = Integer.toString(i);
        }
        System.out.println("DEBUG: Integer.toString took "
        + (System.currentTimeMillis() - start) + " ms for "
        + iterCount + " iterations");

        // test indirect conversion

        start = System.currentTimeMillis();
        for (int i = 0; i < iterCount; i++) {
          String s = "" + i;
        }
        System.out.println("DEBUG: Indirect string conversion took "
          + (System.currentTimeMillis() - start) + " ms for "
          + iterCount + " iterations");
    }
}

Output

DEBUG: String.valueOf took 106 ms for 1000000 iterations
DEBUG: Integer.toString took 92 ms for 1000000 iterations
DEBUG: Indirect string conversion took 271 ms for 1000000 iterations

So the summary is that Integer.toString provides the best performance.

answer Feb 17, 2014 by Salil Agrawal
...