string.IsNullOrEmpty is slower than pattern matching #46063
-
Just came across this: using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace StringTests
{
class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<Benchmark>();
}
}
[MemoryDiagnoser]
public class Benchmark
{
[Params(null, "", "text")]
public string? Text;
[Benchmark]
public bool StringIsNullOrEmpty() => string.IsNullOrEmpty(this.Text);
[Benchmark]
public bool PatternMatching() => this.Text is { Length: 0 };
[Benchmark]
public bool AggressiveInliningPatternMatching() => StringExtensions.AggressiveInliningPatternMatching(this.Text);
[Benchmark]
public bool NoInliningPatternMatching() => StringExtensions.NoInliningPatternMatching(this.Text);
}
public static class StringExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool AggressiveInliningPatternMatching(string? text) => text is { Length: 0 };
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool NoInliningPatternMatching(string? text) => text is { Length: 0 };
}
} BenchmarkDotNet=v0.12.1, OS=Windows 10.0.21277
Being on the ns scale and not on a dedicated system, these values might be meaningless. Nevertheless, surprising. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
StringTests.Benchmark.StringIsNullOrEmpty()
L0000: push ebp
L0001: mov ebp, esp
L0003: mov eax, [ecx+4]
L0006: test eax, eax
L0008: je short L0014
L000a: cmp dword ptr [eax+4], 0
L000e: jbe short L0014
L0010: xor eax, eax
L0012: jmp short L0019
L0014: mov eax, 1
L0019: pop ebp
L001a: ret
StringTests.Benchmark.PatternMatching()
L0000: mov eax, [ecx+4]
L0003: test eax, eax
L0005: je short L0012
L0007: cmp dword ptr [eax+4], 0
L000b: sete al
L000e: movzx eax, al
L0011: ret
L0012: xor eax, eax
L0014: ret |
Beta Was this translation helpful? Give feedback.
-
Answered by @gfoidl - but I can't mark a comment as answer. |
Beta Was this translation helpful? Give feedback.
Answered by @gfoidl - but I can't mark a comment as answer.