Why most Delphi examples use FillChar() to initialize records?

前端 未结 8 2081
离开以前
离开以前 2020-12-13 06:32

I just wondered, why most Delphi examples use FillChar() to initialize records.

type
  TFoo = record
    i: Integer;
    s: string; // not safe in record, b         


        
8条回答
  •  借酒劲吻你
    2020-12-13 07:19

    The question may also be asking:

    • why FillChar
    • and not ZeroMemory?

    There is no ZeroMemory function in Windows. In the header files (winbase.h) it is a macro that, in the C world, turns around and calls memset:

    memset(Destination, 0, Length);
    

    ZeroMemory is the language neutral term for "your platform's function that can be used to zero memory"

    The Delphi equivalent of memset is FillChar.

    Since Delphi doesn't have macros (and before the days of inlining), calling ZeroMemory meant you had to suffer the penalty of an extra function call before you actually got to FillChar.

    So in many ways, calling FillChar is a performance micro-optimization - which no longer exists now that ZeroMemory is inlined:

    procedure ZeroMemory(Destination: Pointer; Length: NativeUInt); inline;
    

    Bonus Reading

    Windows also contains the SecureZeroMemory function. It does the exact same thing as ZeroMemory. If it does the same thing as ZeroMemory, why does it exist?

    Because some smart C/C++ compilers might recognize that setting memory to 0 before getting rid of the memory is a waste of time - and optimize away the call to ZeroMemory.

    I don't think Delphi's compiler is as smart as many other compilers; so there's no need for a SecureFillChar.

提交回复
热议问题