Skip to content

Use base index scale to access address in unsafe #4921

@fo40225

Description

@fo40225

Consider those code

int[] a = { 1, 2 };
int temp;
fixed (int* ptrA = a)
{
    for (int i = 0; i < a.Length; i++)
    {
        temp = ptrA[i];
        temp = temp + i;
        Console.WriteLine(temp.ToString());
    }

    int* tempPtrA = ptrA;
    for (int i = 0; i < a.Length; i++, tempPtrA++)
    {
        temp = *tempPtrA;
        temp = temp + i;
        Console.WriteLine(temp.ToString());
    }
}

In C/C++, first loop will faster than second one because first loop will use

mov         eax,dword ptr a[esi*4]

use only one instruction and get value. and second loop will use extra two instructions to increase pointer

mov         eax,dword ptr [edi]
inc         esi 
lea         edi,[edi+4]

But in C# unsafe code, first loop will use

mov         rcx,qword ptr [rbp-20h]
mov         qword ptr [rbp-38h],rcx
mov         rcx,qword ptr [rbp-38h]
mov         eax,dword ptr [rbp-2Ch]
movsxd      rax,eax  
mov         edx,4  
movsxd      rdx,edx  
imul        rax,rdx  
mov         ecx,dword ptr [rcx+rax]

and cause first one slow than second one. The imul slow down the performance.

If there is no performance penalty for using a scaling factor, why don't just use that instead of imul.

or there have some reason so can't use it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIenhancementProduct code improvement that does NOT require public API changes/additionsoptimizationtenet-performancePerformance related issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions