Jerry Dodge
Jerry Dodge

Reputation: 27276

Does the compiler optimize string concatenation?

I have some cases in my code where I am building a large string of text, such as a complex SQL statement. I intend to put this text together many times in a row, each with some slightly different parameters. I've come to the habit of using a subroutine named just procedure A(const S: String); which simply appends the text (S) to the larger string Text := Text + S + #10 + #13;

I was wondering if this could hinder the performance as opposed to using traditional string concatenation? I am beginning to think the compiler optimizes something like this:

Text := 'some' + ' ' + 'text' + ' ' + 'and' + ' ' + 'such';

to

Text := 'some text and such';

Is this true? Does the compiler optimize this scenario? If so, I may decide to change everything to something like this:

Text := 'select something from sometable st'+#10+#13+
  'join someothertable sot on sot.id = st.sotid'+#10+#13+
  'where sot.somevalue = 1'+#10+#13+
  'order by sot.sorting';

Would this be faster theoretically than

Text:= Text + 'select something from sometable st'+#10+#13;
Text:= Text + 'join someothertable sot on sot.id = st.sotid'+#10+#13;
Text:= Text + 'where sot.somevalue = 1'+#10+#13;
Text:= Text + 'order by sot.sorting';

or how I usually do it:

A('select something from sometable st');
A('join someothertable sot on sot.id = st.sotid');
A('where sot.somevalue = 1');
A('order by sot.sorting');

Upvotes: 4

Views: 415

Answers (2)

David Dubois
David Dubois

Reputation: 3932

Note that putting all concatenations in one expression is still more efficient when non-constant expressions are used. Consider this code:

  A := '*';
  B := 'person';
  C := 'first_name=''Jerry''';

  Q := 'select ';
  Q := Q + A;
  Q := Q + ' from ';
  Q := Q + B;
  Q := Q + ' where ';
  Q := Q + C;

The six statements above will perform 5 separate concatenations. Whereas:

  Q := 'select ' + A + ' from ' + B + ' where ' + C;

will perform a single concatenation. Delphi will allocate the necessary space for the result and copy each of the six values into that space.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612993

An expression like

'a' + 'b'

is evaluated at compile time. Which means that an assignment

str := 'a' + 'b';

results in identical compiled code to

str := 'ab';

On the other hand, for

str := 'a';
str := str + 'b';

the concatenation is performed at runtime.

Upvotes: 9

Related Questions