Does the compiler optimize string concatenation?

I have some cases in my code where I am building a large line of text, such as a complex SQL statement. I intend to combine this text many times in a row, each of which has several slightly different parameters. I'm used to using a routine called just procedure A(const S: String); , which simply adds text ( S ) to the larger line Text := Text + S + #10 + #13;

I was wondering if this could hinder performance rather than using traditional string concatenation? I'm starting to think that the compiler is optimizing something like this:

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

to

 Text := 'some text and such'; 

It's true? Does this scenario optimize this scenario? If so, I can 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'; 

It would 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 as usual I 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'); 
+4
source share
2 answers

Expression like

 'a' + 'b' 

evaluated at compile time. This means that the assignment

 str := 'a' + 'b'; 

outputs the identical compiled code to

 str := 'ab'; 

On the other hand, for

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

concatenation is performed at runtime.

+9
source

Note that adding all concatenations in a single expression is even more efficient when using non-constant expressions. 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; 

In the six statements above, 5 separate concatenations will be performed. Pay attention to:

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

will perform one concatenation. Delphi will allocate the necessary space for the result and copy each of the six values ​​into this space.

0
source

All Articles