1

I've had a few people tell me that things like this are super lazy:

int val = 5;
System.out.println("" + val);
String myStr = "" + val;

Why is this better than String.valueOf(val)? Isn't it doing the exact same thing under the hood?

redux
  • 1,157
  • 10
  • 21

2 Answers2

1

It's not really "better", just shorter, making it easier to read and type. There is (virtually) no ther difference, even though a real purist might, probably, say, this is actually worse, because (at least, in the absence of optimization), this creates an intermediate StringBuilder object, that is then appended a character before being converted into a String, so, this may be spending more ticks, than .valueOf.

Dima
  • 39,570
  • 6
  • 44
  • 70
0

From JLS:

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

Community
  • 1
  • 1
Atri
  • 5,511
  • 5
  • 30
  • 40