[fpc-devel] sub-optimal code for UniqueString
Martin Frb
lazarus at mfriebe.de
Fri Oct 17 15:28:26 CEST 2025
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.
More information about the fpc-devel
mailing list