-
While calculating "half the length rounded up" I played around to see what assembly was generated when using division and modulo operators and how few instructions I could get it down to. For I assume this is because the JIT somehow knows that struct List
{
int M0(List<int> a) => (a.Count / 2) + (a.Count % 2);
int M1(List<int> a) => (a.Count >>> 1) + (a.Count & 1);
int M2(List<int> a) => (int)(((uint)a.Count / 2) + ((uint)a.Count % 2));
} List.M0(System.Collections.Generic.List`1<Int32>)
L0000: mov eax, [rdx+0x10]
L0003: mov edx, eax
L0005: shr edx, 0x1f
L0008: add edx, eax
L000a: sar edx, 1
L000c: mov ecx, eax
L000e: shr ecx, 0x1f
L0011: add ecx, eax
L0013: and ecx, 0xfffffffe
L0016: sub eax, ecx
L0018: add eax, edx
L001a: ret
List.M1(System.Collections.Generic.List`1<Int32>)
L0000: mov eax, [rdx+0x10]
L0003: mov edx, eax
L0005: shr edx, 1
L0007: and eax, 1
L000a: add eax, edx
L000c: ret
List.M2(System.Collections.Generic.List`1<Int32>)
L0000: mov eax, [rdx+0x10]
L0003: mov edx, eax
L0005: shr edx, 1
L0007: and eax, 1
L000a: add eax, edx
L000c: ret struct Array
{
int M0(int[] a) => (a.Length / 2) + (a.Length % 2);
int M1(int[] a) => (a.Length >>> 1) + (a.Length & 1);
int M2(int[] a) => (int)(((uint)a.Length / 2) + ((uint)a.Length % 2));
} Array.M0(Int32[])
L0000: mov eax, [rdx+8]
L0003: mov edx, eax
L0005: shr edx, 1
L0007: and eax, 1
L000a: add eax, edx
L000c: ret
Array.M1(Int32[])
L0000: mov eax, [rdx+8]
L0003: mov edx, eax
L0005: shr edx, 1
L0007: and eax, 1
L000a: add eax, edx
L000c: ret
Array.M2(Int32[])
L0000: mov eax, [rdx+8]
L0003: mov edx, eax
L0005: shr edx, 1
L0007: and eax, 1
L000a: add eax, edx
L000c: ret |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
An array is a fundamental type that is part of the runtime, so the JIT can make various assumptions about it. |
Beta Was this translation helpful? Give feedback.
An array is a fundamental type that is part of the runtime, so the JIT can make various assumptions about it.
List<T>
is, strictly speaking, just a library type like any other, so the JIT can't make assumptions about what the_size
field means.