Why you need to make your string parameter a const

I have often wanted to point this out, but didn't really feel the need to, until today, when I was debugging into the RTL.

When you have a string parameter, the compiler makes a call to the RTL routine _UStrAddRef, and _UStrClr.
When you have multiple string parameters, the compiler makes a call for each string parameter to _UStrAddRef, and one call to _UStrArrayClr. In addition, the compiler will compile code similar to a try finally sequence as well.

If you do not make any changes to the string parameter, it is better to make that string parameter a const.

So, assuming you have the following code pattern:

procedure AName(param1: string)

changing it to:

procedure AName(const param1: string)

reduces the 2 calls generated by the compiler.

Here's the disassembly for the procedure X(S1, S2: string)

00524AF4 55 push ebp
00524AF5 8BEC mov ebp,esp
00524AF7 83C4F8 add esp,-$08
00524AFA 8955F8 mov [ebp-$08],edx
00524AFD 8945FC mov [ebp-$04],eax
00524B00 8B45FC mov eax,[ebp-$04]
00524B03 E8B058EEFF call @UStrAddRef
00524B08 8B45F8 mov eax,[ebp-$08]
00524B0B E8A858EEFF call @UStrAddRef
00524B10 33C0 xor eax,eax
00524B12 55 push ebp
00524B13 68394B5200 push $00524b39
00524B18 64FF30 push dword ptr fs:[eax]
00524B1B 648920 mov fs:[eax],esp
00524B1E 33C0 xor eax,eax
00524B20 5A pop edx
00524B21 59 pop ecx
00524B22 59 pop ecx
00524B23 648910 mov fs:[eax],edx
00524B26 68404B5200 push $00524b40
00524B2B 8D45F8 lea eax,[ebp-$08]
00524B2E BA02000000 mov edx,$00000002
00524B33 E8FC57EEFF call @UStrArrayClr
00524B38 C3 ret
00524B39 E9B24DEEFF jmp @HandleFinally
00524B3E EBEB jmp $00524b2b
00524B40 59 pop ecx
00524B41 59 pop ecx
00524B42 5D pop ebp
00524B43 C3 ret

and here's the disassembly for Y(const S1, S2: string):

00524B44 55 push ebp
00524B45 8BEC mov ebp,esp
00524B47 83C4F8 add esp,-$08
00524B4A 8955F8 mov [ebp-$08],edx
00524B4D 8945FC mov [ebp-$04],eax
00524B50 59 pop ecx
00524B51 59 pop ecx
00524B52 5D pop ebp
00524B53 C3 ret

As you can see, without the const, the generated code is more verbose.

Published Fri, 8 Dec 2017 @ 9:40 AM by chuacw
Related articles: ,