tags:

views:

262

answers:

4

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])
+3  A: 

Here's a third option:

s:=Concat(V1,V2);
RRUZ
That is identical to s := V1 + V2; Concat is a compiler "magic" function that is collapsed to call the same internal helper as <str> + <str>.
Allen Bauer
While it's identical behind the scenes, I find this easier to read in code than the "+" operator, especially with long strings or multiple concatenations. This goes back to Mason's practical point of what's "best".
Argalatyr
+8  A: 

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.

Mason Wheeler
Usually "best" in the end comes down to "Do I understand why I wrote the code this way 3 months from now?".
Jeroen Pluimers
+6  A: 

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!'
Craig Stuntz
You might want to explain that statement, it's probably not obvious to a lot of Delphi users why Format works with i18n.
Jeroen Pluimers
OK, how's this?
Craig Stuntz
Right what I hoped for :-)
Jeroen Pluimers
A: 

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.

lkessler