Why is creating an array with inline initialization so slow?

后端 未结 2 1459
一生所求
一生所求 2021-02-02 07:33

Why is inline array initialization so much slower than doing so iteratively? I ran this program to compare them and the single initialization takes many times longer than doing

2条回答
  •  猫巷女王i
    2021-02-02 07:56

    Static array initializes are implemented bit differently. It will store the bits in the assembly as a embedded class which will be named something like ....

    What it does is stores the array data as bits inside the assembly in some special location; which will then be loaded from the assembly and it will call RuntimeHelpers.InitializeArray to initialize the array.

    Do note that if you use reflector to view the compiled source as C# you'll not notice anything what I'm describing here. You'll need to look at the IL view in reflector or any such decompiling tools.

    [MethodImpl(MethodImplOptions.InternalCall), SecuritySafeCritical, __DynamicallyInvokable]
    public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle);
    

    You can see this is implemented in CLR (marked as InternalCall), which then maps to COMArrayInfo::InitializeArray (ecall.cpp in sscli).

    FCIntrinsic("InitializeArray", COMArrayInfo::InitializeArray, CORINFO_INTRINSIC_InitializeArray)
    

    COMArrayInfo::InitializeArray (lives in comarrayinfo.cpp) is the magical method which initializes the array with the value from bits embedded in assembly.

    I'm not sure why this takes a lot of time to complete; I don't have good explanations for that. I guess it is because it goes and pulls the data from the physical assembly? I'm not sure. You can dig into the methods by yourself. But you can get some idea that it doesn't gets compiled to as what you see in your code.

    You can use tools like IlDasm, and Dumpbin to find more about this and of course download sscli.

    FWIW: I've got this information from Pluralsight course by "bart de smet"

提交回复
热议问题