Search code examples
javastringsubstringstring-formattingstringbuilder

Difference between formatted string and simple string


What is the difference between these code blocks - is there any difference in performance or memory or other?

the first code is:

String name = "Jack";
String familyName = "Hunter";

String result = String.format("Your name is %s %s",name, familyName);

and second code is:

String name = "Jack";
String familyName = "Hunter";

String result = "Your name is " + name + " " + familyName;

thank you for attentions ;-)


Solution

  • There's no difference in terms of the output it produces. The result variable will have the same contents in each case.

    But String.format() is there so that you can do more powerful formatting, including specifying number of decimal places for floating point numbers, and the like.

    I would expect the String.format() version to be relatively slow, simply because it's more powerful, and has to check the contents of the format string before performing essentially the same operation as you're doing in your second version. In other words, it has to spend some time working out what you want to do, whereas in the second version, the compiler can work it out for itself.

    But, really, choosing one of your snippets over the other here for performance reasons looks like the kind of micro-optimisation that will almost never pay off. Unless you have a clear need for performance (i.e., this is running in a tight loop for something performance-critical), you should go for the one that's more readable.