Skip to content

Instantly share code, notes, and snippets.

@nyctef
Created October 15, 2021 12:35
Show Gist options
  • Save nyctef/021ca4c2ef88dea0d95ed1f2ce828f7b to your computer and use it in GitHub Desktop.
Save nyctef/021ca4c2ef88dea0d95ed1f2ce828f7b to your computer and use it in GitHub Desktop.
String.Equals vs Object.ReferenceEquals (and how string interning can make things fast)
BenchmarkDotNet=v0.12.1, OS=macOS 11.6 (20G165) [Darwin 20.6.0]
Intel Core i5-6267U CPU 2.90GHz (Skylake), 1 CPU, 4 logical and 2 physical cores
.NET Core SDK=5.0.401
  [Host]     : .NET Core 5.0.10 (CoreCLR 5.0.1021.41214, CoreFX 5.0.1021.41214), X64 RyuJIT
  DefaultJob : .NET Core 5.0.10 (CoreCLR 5.0.1021.41214, CoreFX 5.0.1021.41214), X64 RyuJIT

Method Mean Error StdDev
StringEquals 7.3439 ns 0.0302 ns 0.0252 ns
ReferenceEquals 0.0600 ns 0.0034 ns 0.0032 ns
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<DebugSymbols>true</DebugSymbols>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Optimize>true</Optimize>
<Configuration>Release</Configuration>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.12.1" />
<PackageReference Include="BenchmarkDotNet.Diagnostics.Windows" Version="0.12.1" Condition="'$(OS)' == 'Windows_NT'"/>
</ItemGroup>
</Project>
using System;
using BenchmarkDotNet;
using BenchmarkDotNet.Attributes;
namespace string_comparison_bench
{
public class Benchmarks
{
private string str1 = "string1";
private string str2 = "string2";
[Benchmark]
public bool StringEquals()
{
return str1.Equals(str1) && str1.Equals(str2);
}
[Benchmark]
public bool ReferenceEquals()
{
return ReferenceEquals(str1, str1) && ReferenceEquals(str1, str2);
}
}
}
using BenchmarkDotNet.Running;
namespace string_comparison_bench
{
public class Program
{
public static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<Benchmarks>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment