Disable Quick JIT
From .NET 7 onwards, to disable Quick JIT, edit the application project file (.csproj) as follows.
<Project Sdk="Microsoft.NET.Sdk">
...
<PropertyGroup>
...
<TieredCompilationQuickJit>false</TieredCompilationQuickJit>
...
</PropertyGroup>
...
</Project>
Application startup time increases, but optimisation improves and runtime performance should be faster.
Reference: https://qiita.com/rougemeilland/items/b8b4b045b82a294a56de
Checking 0 <= n && n < MAX for an integer n
Instead of writing:
if (n >= 0 && n < MAX)
prefer:
if ((uint)n < (uint)MAX)
This reduces the number of comparisons. The cast to uint has virtually no overhead.
ArrayPool<T>.Shared
For temporary arrays used inside loops or similar contexts, avoid new[] and instead rent from the shared pool as shown below. This is more memory-efficient, faster, and avoids GC pressure.
byte[] array = ArrayPool<byte>.Shared.Rent(20); // Rent a buffer
// ... use array ...
ArrayPool<byte>.Shared.Return(array); // Return the borrowed buffer
Reference: https://ikorin2.hatenablog.jp/entry/2021/12/20/225208
.Where(…).Select(…)
Always chain .Where() before .Select(). The JIT compiler can optimise this ordering.
Debug branching without #if DEBUG
Define the following static class and use AssemblyState.IsDebug in conditional expressions.
internal static class AssemblyState {
public const bool IsDebug =>
#if DEBUG
true;
#else
false;
#endif
}
This keeps the code concise and has no effect on runtime performance.
Reference: https://ikorin2.hatenablog.jp/entry/2020/06/27/065646
Returning ordinal strings (1st, 2nd, 3rd, …)
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",
};
}