When to use short?

前端 未结 4 603
心在旅途
心在旅途 2021-01-20 03:23

Say I\'m looping through like 20/30 objects or in any other case where I\'m dealing with smaller numbers, is it a good practice to use short instead of int?

I mean w

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-20 03:36

    "is it a good practice to use short instead of int?"

    First of all, this is a micro optimization that will not achieve the expected results: increase speed or efficiency.

    Second: No, not really, the CLR internally still uses 32 bit integers (Int32) to perform the iteration. Basically it converts short to Int32 for computation purposes during JIT compilation.

    Third: Array indexes are Int32, and the iterating short variable is automatically converted to int32 when used as an array indexer.

    If we take the next code:

        var array = new object[32];
        var x = array.Length;
        for (short i = 0; i < x; i++)
            Method(array[i]);
    

    And disassemble it, you can clearly see at 00000089 inc eax that at machine level an 32 bit register was used for the iterating variable (eax), which is next truncated to 16 bit 0000008a movsx eax,ax so there are no benefits from using a short oppossed to using an int32, actually there might be a slight performance loss due to extra instructions that need to be executed.

    00000042  nop 
                var array = new object[32];
    00000043  mov         ecx,64B41812h 
    00000048  mov         edx,20h 
    0000004d  call        FFBC01A4 
    00000052  mov         dword ptr [ebp-50h],eax 
    00000055  mov         eax,dword ptr [ebp-50h] 
    00000058  mov         dword ptr [ebp-40h],eax 
                var x = array.Length;
    0000005b  mov         eax,dword ptr [ebp-40h] 
    0000005e  mov         eax,dword ptr [eax+4] 
    00000061  mov         dword ptr [ebp-44h],eax 
                for (short i = 0; i < x; i++)
    00000064  xor         edx,edx 
    00000066  mov         dword ptr [ebp-48h],edx 
    00000069  nop 
    0000006a  jmp         00000090 
                    Method(array[i]);
    0000006c  mov         eax,dword ptr [ebp-48h] 
    0000006f  mov         edx,dword ptr [ebp-40h] 
    00000072  cmp         eax,dword ptr [edx+4] 
    00000075  jb          0000007C 
    00000077  call        657A28F6 
    0000007c  mov         ecx,dword ptr [edx+eax*4+0Ch] 
    00000080  call        FFD9A708 
    00000085  nop 
                for (short i = 0; i < x; i++)
    00000086  mov         eax,dword ptr [ebp-48h] 
    00000089  inc         eax 
    0000008a  movsx       eax,ax 
    0000008d  mov         dword ptr [ebp-48h],eax 
    00000090  mov         eax,dword ptr [ebp-48h] 
    00000093  cmp         eax,dword ptr [ebp-44h] 
    00000096  setl        al 
    00000099  movzx       eax,al 
    0000009c  mov         dword ptr [ebp-4Ch],eax 
    0000009f  cmp         dword ptr [ebp-4Ch],0 
    000000a3  jne         0000006C
    

提交回复
热议问题