Which approach is better and why ?
If I write
cmissValue = String.valueOf(callDBDatasource.cMiss());
or
cmissValue = "" + callDBDatasource.cMiss();
What should be the approach?
Which approach is better and why ?
If I write
cmissValue = String.valueOf(callDBDatasource.cMiss());
or
cmissValue = "" + callDBDatasource.cMiss();
What should be the approach?
"" + callDBDatasource.cMiss();
Will compile to:
new StringBuilder().append("").append(callDBDatasource.cMiss()).toString();
This will create a new object and is therefore significantly slower. See this question: Is string concatenaion really that slow?
This will be useful here (section "Converting numbers to Strings"): http://www.odi.ch/prog/design/newbies.php
Shortly:
String.valueOf(callDBDatasource.cMiss());
For those interested, I've modelled both cases and generated bytecode for them.
Here's a program for the first case:
import java.util.Random;
public class Test1 {
public static void main(String[] args) {
long l = new Random().nextLong();
String s = String.valueOf(l);
System.out.println(s);
}
}
...and here's the bytecode:
0: new #2; //class java/util/Random
3: dup
4: invokespecial #3; //Method java/util/Random."<init>":()V
7: invokevirtual #4; //Method java/util/Random.nextLong:()J
10: lstore_1
11: lload_1
12: invokestatic #5; //Method java/lang/String.valueOf:(J)Ljava/lang/String;
15: astore_3
16: getstatic #6; //Field java/lang/System.out:Ljava/io/PrintStream;
19: aload_3
20: invokevirtual #7; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
23: return
Which is what you would expect.
Now, here's a program modelling the second case:
import java.util.Random;
public class Test2 {
public static void main(String[] args) {
long l = new Random().nextLong();
String s = "" + l;
System.out.println(s);
}
}
...and here's the bytecode:
0: new #2; //class java/util/Random
3: dup
4: invokespecial #3; //Method java/util/Random."<init>":()V
7: invokevirtual #4; //Method java/util/Random.nextLong:()J
10: lstore_1
11: new #5; //class java/lang/StringBuilder
14: dup
15: invokespecial #6; //Method java/lang/StringBuilder."<init>":()V
18: ldc #7; //String
20: invokevirtual #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
23: lload_1
24: invokevirtual #9; //Method java/lang/StringBuilder.append:(J)Ljava/lang/StringBuilder;
27: invokevirtual #10; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
30: astore_3
31: getstatic #11; //Field java/lang/System.out:Ljava/io/PrintStream;
34: aload_3
35: invokevirtual #12; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
38: return
As you can see, many more bytecodes are produced than the first case. You can also see (at 11 through 27) that a StringBuilder
is used to concatenate the values, as mentioned in the accepted answer.