Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it slower to use String.valueOf(myString)?

Tags:

java

string

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

like image 364
WhiskThimble Avatar asked Dec 08 '22 15:12

WhiskThimble


2 Answers

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.

like image 60
Petr Janeček Avatar answered Dec 11 '22 10:12

Petr Janeček


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 Strings.

like image 23
jason Avatar answered Dec 11 '22 11:12

jason