This is just an informational question, I don't need you to tell me that I shouldn't use it.
My question is : if I use string1 = String.valueOf(string2);
, is it slower than string1 = string2;
?
The thing is : I would like to use a method to get a String from integers, doubles ect... and strings. I just would like to know if I should create another method.
Thanks, and sorry if this is a dupplicate, I didn't find it
Technically, yes. It is slower by invoking two method calls both of which do no work (valueOf()
and toString()
on the String object).
Practically, not at all, unless you're doing it millions of times (and nothing else to it). Invoking two almost no-op methods doesn't cost you anything.
Oh, probably slightly slower since String.valueOf(object o)
is effectively o.toString()
if o
is not null
. So, you have the overhead of method calls that could or could not be inlined. The effect is however extremely small. But that is not what matters here, what matters is clarity.
string1 = string2
more clearly expresses your intent than
string1 = String.valueOf(string2);
Therefore, for this reason, use the former. This is a no brainer.
You didn't say if it's the case or not, but I feel comfortable assuming that you meant to tell us that string1
and string2
are String
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With