Conditional default() introduces unconditional FillChar
Original Reporter info from Mantis: runewalsh
-
Reporter name:
Original Reporter info from Mantis: runewalsh
- Reporter name:
Description:
The code
...
if condition then x := default(XType);
does something like
var
tempX: XType;
begin
FillChar(tempX, sizeof(tempX), 0);
...
if condition then x := tempX;
end;
Note that:
(1) FillChar is inserted at the beginning of the procedure, even if its actual usage is conditional;
(2) FillChar fills a temporary variable, which is then copied into the lvalue as if it was a general case of the assignment.
So presently, default() that is never executed still does FillChar, i.e. half of its work:
ConditionalDefault: 18.7 ns/call
ConditionalDefaultWorkaround: 1.2 ns/call
...and even if executed, manual FillChar(x, sizeof(x), 0) is twice as fast:
UnconditionalDefault: 34.8 ns/call
UnconditionalFillChar: 18.2 ns/call
So, why won't default() call FillChar on the target variable (at least unmanaged) right away?
Additional information:
Managed types have a problem vaguely resembling (1): they are initialized at the beginning of the procedure and finalized at the end, and it slows the entire procedure down, even if they are only used in a rarely-taken branch. But I don't hope this will be fixed in the nearest eternity, while that ‘default’ thing seems easy.
Mantis conversion info:
- Mantis ID: 38472
- Build: FPC 3.3.1-r47986 [2021/01/03]
- Version: 3.3.1