Disabling Quick JIT

From .NET 7 onward, you can disable Quick JIT by editing the application project file (.csproj).

<Project Sdk="Microsoft.NET.Sdk">
  .....
  <PropertyGroup>
    .....
    <TieredCompilationQuickJit>false</TieredCompilationQuickJit>
    .....
  </PropertyGroup>
  .....
</Project>

Although application startup time will be slower, optimization should improve and execution speed is expected to increase.

Reference: https://qiita.com/rougemeilland/items/b8b4b045b82a294a56de


Checking 0 <= n && n < MAX for an Integer n

if (n >= 0 && n < MAX)

Instead of writing the above, write:

if ((uint)n < (uint)MAX)

This reduces the number of comparisons. The cost of casting to uint is virtually zero.


ArrayPool<T>.Shared

For temporary arrays used inside loops, instead of using new [], allocate arrays as follows. It is more memory-efficient, faster, and avoids GC.

byte[] array = ArrayPool<byte>.Shared.Rent(20);// Obtain a buffer

// Processing using array

ArrayPool<byte>.Shared.Return(array);// Return the borrowed buffer

Reference: https://ikorin2.hatenablog.jp/entry/2021/12/20/225208


.Where(...).Select(...)

Always use Where and Select in this order when chaining them. The JIT will optimize them.


Debug Branching Without #if DEBUG

Create the following static class and use AssemblyState.IsDebug in conditional statements.

internal static class AssemblyState {
  public const bool IsDebug =>
  #if DEBUG
    true;
  #else
    false;
  #endif
}

This shortens the code and has no impact on execution speed.

Reference: https://ikorin2.hatenablog.jp/entry/2020/06/27/065646


Returning a Number with Ordinal Suffix (st, nd, rd, th)

 public static string Ordinal(this int number)
 {
     var ones = number % 10;
     var tens = Math.Floor(number / 10f) % 10;
     if (tens == 1)
         return number + "th";
     else return ones switch
     {
         1 => number + "st",
         2 => number + "nd",
         3 => number + "rd",
         _ => number + "th",
     };
 }
contents