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.