Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Last active February 28, 2020 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atifaziz/c7968654db9ac4021faa6ff610bb3793 to your computer and use it in GitHub Desktop.
Save atifaziz/c7968654db9ac4021faa6ff610bb3793 to your computer and use it in GitHub Desktop.
Demo that RyuJIT eliminates unreachable "typeof(T)==typeof(…)" branches in generic instantiations of a method

What's this?

Found an interesting comment in SqlDataReader's source code:

// this block of type specific shortcuts uses RyuJIT jit behaviours to achieve fast implementations of the primitive types
// RyuJIT will be able to determine at compilation time that the typeof(T)==typeof(<primitive>) options are constant
// and be able to remove all implementations which cannot be reached. this will eliminate non-specialized code for 

This test carried out in SharpLab proves it to be true!

; Core CLR v4.700.19.57202 (coreclr.dll) on x86.
C..ctor()
L0000: ret
C.M[[System.Int32, System.Private.CoreLib]](Int32, Int32, Int32)
L0000: mov eax, edx
L0002: ret 0x8
C.M[[System.Int16, System.Private.CoreLib]](Int16, Int16, Int16)
L0000: mov eax, [esp+0x8]
L0004: movsx eax, ax
L0007: ret 0x8
C.M[[System.Byte, System.Private.CoreLib]](Byte, Byte, Byte)
L0000: mov eax, [esp+0x4]
L0004: movzx eax, al
L0007: ret 0x8
using SharpLab.Runtime;
public class C {
[JitGeneric(typeof(int)),
JitGeneric(typeof(short)),
JitGeneric(typeof(byte))]
public T M<T>(T a, T b, T c) {
if (typeof(T) == typeof(int)) {
return (T)(object)a;
}
if (typeof(T) == typeof(short)) {
return (T)(object)b;
}
return c;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment