Reputation: 409
I have an object that on initialisation it takes in a string to identify its name.
String name = "MyObject" + Integer.toString(objectNum);
object = new Object(name);
In the example above the name follows a convention such that an integer is concatenated with a string "MyObject". A colleague complained that the way I wrote this code is actually terrible from a performance perspective because of the int to string conversion. The number is received as an int and there's nothing I can do about that. The object parameter MUST take in a string. How can I make this quicker? Would using string format help?
Upvotes: 0
Views: 268
Reputation: 46
I'd say your code is fine as it is from a performance perspective. The "MyObject" literal will be interned and then just reused, and every time you assign "name" you create a new string anyway, so I don't really see how that could be made to run that much faster. (Maybe storing objectNum in the object instead of name, and then only concatenating if you want to print the whole identifier? I guess you'd save a few femtoseconds that way...)
Personally, I'd use this approach (mainly for readability, and it's not the fastest in terms of execution): String name = String.format("MyObject%d", objectNum);
Upvotes: 0
Reputation: 140328
"MyObject" + objectNum
is best. objectNum
is automatically effectively converted to a String
.
Focus on readability, let Java worry about the best way to concatenate it.
The performance problem with "MyObject" + Integer.toString(objectNum)
is that it explicitly creates a String
from the int
, and then concatenates it to the preceding String
. It tends to be compiled to something like:
new StringBuilder("MyObject").append(Integer.toString(objectNum)).toString()
Which is... a working approach.
But, StringBuilder
has append(int)
, which is able to do things more efficiently if it knows the parameter is an int
. "MyObject" + objectNum
still becomes something like:
new StringBuilder("MyObject").append(objectNum).toString()
which just avoids creating the String
for objectNum
.
With all that said, the JIT could well recognize the "MyObject" + Integer.toString(objectNum)
pattern, and execute it effectively like "MyObject" + objectNum
(or vice versa, ofc, if it determines that is more efficient), so there could be no practical performance difference.
Given that, you should use the form which is easier to read, and just trust that the JIT will do its thing and execute the code as fast as it can be executed.
Upvotes: 5