I'm curious about what happens with this piece of code in Delphi 2010:
function foo: WideString;
var
myUnicodeString: UnicodeString;
begin
for i:=1 to 1000 do
begin
myUnicodeString := ... something ...;
result := result + myUnicodeString; // This is where I'm interested
end;
end;
How many string conversions are involved, and are any particularly bad performance-wise?
I know the function should just return a UnicodeString instead, but I've seen this anti-pattern in the VCL streaming code, and want to understand the process.
To answer your question about what the code is actually doing, this statement:
Does the following:
calls
System._UStrFromWStr()to convertResultto a tempUnicodeStringcalls
System._UStrCat()to concatenatemyUnicodeStringonto the tempcalls
System._WStrFromUStr()to convert the temp to aWideStringand assign it back toResult.There is a
System._WStrCat()function for concatenating aWideStringonto aWideString(andSystem._UStrCat()forUnicodeString). If CodeGear/Embarcadero had been smarter about it, they could have implemented aSystem._WStrCat()overload that takes aUnicodeStringas input and aWideStringas output (and vice versa for concatenating aWideStringonto aUnicodeString). That way, no tempUnicodeStringconversions would be needed anymore. BothWideStringandUnicodeStringare encoded as UTF-16 (well mostly, but I won't get into that here), so concatenating them together is just a matter of a single allocation and move, just like when concatenating twoUnicodeStrings or twoWideStrings together.