What is the best approach, simple string concatenation or string.format
?
For instance, what is the better to use:
s:=v1+' '+v2
or
s:=format('%S %S',[v1,v2])
What is the best approach, simple string concatenation or string.format
?
For instance, what is the better to use:
s:=v1+' '+v2
or
s:=format('%S %S',[v1,v2])
Depends on your criteria for "best". If all you're doing is concatenating two strings, I'd go with the + operator. It's obvious what you're trying to do and easy to read, and it's a little bit faster because it doesn't have to use variants. (Have you looked at what format
actually does under the hood? it's kinda scary!)
The major advantage of format
is that it lets you make a single string and store it somewhere, such as in a text file or a resourcestring, and gather other parameters later. This makes it useful for more complex tasks. But if all you need to do is stick two strings together, it's kinda overkill IMO.
Format works with internationalization, making it possible to localize your app. Concatenation does not. Hence, I favor format for any display which may have to be produced in a culture-dependent manner.
Update: The reason format works for internationalization is that not all languages express everything in the same order. A contrived example would be:
resourcestring
sentence = ' is ';
var
subject = 'Craig';
adjective = 'helpful';
begin
WriteLn(subject + sentence + adjective + '!');
This works, and I can customize with a resourcestring, but in Spanish I would write, "¡Qué servicial es Craig!" The resourcestring doesn't help me. Instead I should write:
resourcestring
sentence = '%S is %S!'; // ES: '¡Qué %1:S es %0:S!'
I use:
s := v1 + ' ' + v2;
It's clearest and easiest to understand.
That is the most important thing.
You may find a construct that is marginally more efficient, e.g. using TStringBuilder in Delphi 2009. If efficiency is of utmost importance, then do what's necessary in the two or three most critical lines. Everywhere else, use code and constructs that are clear and easy to understand.