String someText = “”+obj;
Most of the checkers like checkstyle, PMD will raise issue that this could be changed to static constant.
So finally I just want to check how this is really working from performance point of view.
Here is simple test - loop where new instance of string is created using 3 different methods:
- “”+obj
- CONSTANT+obj
- String.valueOf((Object)obj)
public class StringValueTest { private static final String EMPTY = ""; @Test public void test() { String aa = "test"; int loops = 1000000; String x1 = null, x2= null, x3= null; long s1, s2, s3; long e1, e2, e3; s1 = System.currentTimeMillis(); for (int i = 0; i < loops; i++) { x1 = "" + aa; } e1 = System.currentTimeMillis() - s1; s2 = System.currentTimeMillis(); for (int i = 0; i < loops; i++) { x2 = EMPTY + aa; } e2 = System.currentTimeMillis() - s2; s3 = System.currentTimeMillis(); for (int i = 0; i < loops; i++) { x3 = String.valueOf((Object)aa); } e3 = System.currentTimeMillis() - s3; System.out.println(loops +" times calling to \"\"+aa takes " + e1+ "ms /"+x1); System.out.println(loops +" times calling to EMPTY+aa takes " + e2+ "ms /"+x2); System.out.println(loops +" times calling to String.valueOf(aa) " + e3+ "ms /"+x3); } }
And results:
1000000 times calling to ""+aa takes 32ms /test 1000000 times calling to EMPTY+aa takes 21ms /test 1000000 times calling to String.valueOf(aa) 4ms /test
Yes, introducing constant speed up execution around 30-50%.
However for performance we should use String.valueOf(obj) which is 10 times quicker!