Sunday, July 24, 2016

Effect of using a constant parameter for string types (revisited)

Long eight years ago i wrote an post about using const for string parameters and effects in generated code. It showed benefits in using const for string types but was far from difference showed with similar test done with Delphi. I never bothered to replicate in Freepascal, i took it as granted.

As the discussion arose in forum, i decided to do a test equals to Delphi one, basically just using the parameter without modifying it, by the way, the most common usage.

I compared
procedure ByValueReadOnly(V: String);
begin
  DoIt(V);
end;
with
procedure ByReferenceReadOnly(const V: String);
begin
  DoIt(V);
end;    
The result talks by itself

Also compared
procedure ByValue(V: String);
begin
  V := V + 'x';
  DoIt(V);
end;
with
procedure ByReference(const V: String);
var
  S: String;
begin
  S := V + 'x';
  DoIt(S);
end;
The generated code is similar, size and performance wise.

For those that underestimate the impact of such differences, read this.

For the curious (or the wary), i uploaded the code.

No comments: