Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-devel / 2025-10

sub-optimal code for UniqueString

1 message · 1 person ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Martin Frb

Well, I know its just a function, and the compiler does not know.... (at least 3.2.3 / don't know if 3.3.1 is doing better).

But in the below code, uniquestring has to make a copy of s, even though that would not really be needed.

When "s" is assigned the result of "bar", then that result is in a temporary variable (which is passed by ref to bar). That temp var has a reference, so the ref count is 2.
(the temp string is only dec-ref-ed in the implicit finally of foo).

Because of this, UniqueString must copy s, as it has a refcnt > 1.

If the compiler could detect this, it could first dec-ref the temp string, then UniqueString would see the refcnt of 1, and be done.

This may apply in many other cases, like if a string gets modified and triggers copy on write.
It may be worth considering to dec-ref temp strings earlier?

program uniq_ref_str;
{$Mode objfpc}{$H+}
uses SysUtils;
function bar: AnsiString;
begin
   Result := IntToStr(Random(99));
end;
procedure foo;
var s: ansistring;
begin
   s := IntToStr(Random(99));
   write(s);
   s := bar;
   UniqueString(s);
   write(s);
end;
begin
   foo;
end.

Reply by email