Saturday, November 15, 2008

Effect of using a constant parameter for string types

Is not rare to find implementations of procedures/functions/methods that uses a value parameter for read only string arguments. While i always use constant parameters for such cases, the real benefit of this code practice was not clear. Until today.

I made a small application that implements two versions of a procedure identical except by the type of parameter (Value vs Constant)...

program asmConstParameter;

{$Mode ObjFpc}
{$H+}

uses
SysUtils, Types;

procedure DoIt(V: String);
begin
Writeln(V);
end;

procedure ByValue(V: String);
var
S: String;
begin
S := V;
DoIt(S);
end;

procedure ByReference(const V: String);
var
S: String;
begin
S := V;
DoIt(S);
end;

var
X: String;

begin
X := 'Test';
ByValue(X);
ByReference(X);
end.

...and examined the assembler output. See the difference yourself. Using optimizations through -O compiler options does not change the produced code.

So using a constant parameter has a practical effect, is not only a good code practice.

BTW: just for curiosity i put {$IMPLICITEXCEPTIONS OFF} in the program header. Not bad. Be aware that this info is here just for curiosity ;-) .

UPDATE: Using constant arguments also benefits ShortString types. See.

6 comments:

Unknown said...

Luis,
We are looking for help with Lazarus on Linux. We are trying to connect to MS SQL Server from Lazarus running on Linux (using Zeos) and we cannot get it running. Do you know anyone who could help us?

Luiz Américo said...

Sorry, i don't have experience with MS SQL Server.

Try Lazarus forum or Zeos Forum

leledumbo said...

Well... that's because the String type is redefined as AnsiString. What if you use ShortString instead?

Luiz Américo said...

There's also a difference. I'll update the post with this info.

zooplah said...

That's interesting. I've always shied away from const parameters because I feared portability issues, but maybe it's worth it :)

Steve Claridge said...

I think that using const parameters makes more readable code. It means that you can tell that a parameter is not modified simply by looking at the function signature rather than having to search through the code.

@Leledumbo

AnsiString types can be passed by value too. There's a definite performance gain with const params.