Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the Guid.ToString() format specifier rather than the string.Replace() method #3242

Merged
merged 2 commits into from
Jan 11, 2022

Conversation

pcameron-
Copy link
Contributor

Description

Using the Guid.ToString() method format specifier rather than the string.Replace() method is 1.6x~ faster and allocates half the memory.

Documentation

https://docs.microsoft.com/en-us/dotnet/api/system.guid.tostring#system-guid-tostring(system-string)

Code playground of .ToString() vs .Replace()

https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEUCuA7AHwAEAmARgFgAoagNwEMoACAcxwEsATJgXiYHEOnAHQA5GAHdBXABQBKANzU6jJhgC2ABzK9WQ4QBUIAZQxR2eFvOEAlGJoA29MDBkAiOG7RMiZAAzCAKJaGACeiirMGpokumxchiZmFlZuom4RNFS+AJwy0WSZuflaJEVkeQW8fNFlSlRAA==

Benchmark

BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19044.1415 (21H2)
AMD Ryzen 7 2700X, 1 CPU, 16 logical and 8 physical cores
.NET SDK=6.0.100
  [Host]    : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
  MediumRun : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT

Job=MediumRun  IterationCount=15  LaunchCount=2  
WarmupCount=10  
Method Runtime Mean Error StdDev Ratio RatioSD Rank Gen 0 Allocated
Replace .NET 6.0 317.8 ns 2.12 ns 3.05 ns 1.00 0.00 2 0.0439 184 B
StringFormat .NET 6.0 193.3 ns 2.40 ns 3.59 ns 0.61 0.01 1 0.0210 88 B
Replace .NET Core 3.1 332.7 ns 4.61 ns 6.90 ns 1.00 0.00 2 0.0439 184 B
StringFormat .NET Core 3.1 198.4 ns 2.41 ns 3.61 ns 0.60 0.02 1 0.0210 88 B
Replace .NET Framework 4.7.2 561.6 ns 1.38 ns 1.98 ns 1.00 2 0.2136 168 B
StringFormat .NET Framework 4.7.2 395.9 ns 0.94 ns 1.32 ns 0.70 1 0.1016 80 B

Benchmark Code

[Benchmark(Baseline = true)]
public string Replace()
{
    return Guid.NewGuid().ToString().Replace("-", string.Empty);
}

[Benchmark]
public string StringFormat()
{
    return Guid.NewGuid().ToString("N");
}

@nohwnd nohwnd self-assigned this Jan 11, 2022
@nohwnd
Copy link
Member

nohwnd commented Jan 11, 2022

Waiting for #3243 will merge that once it is in main.

@Haplois Haplois enabled auto-merge (squash) January 11, 2022 11:53
@Haplois
Copy link
Contributor

Haplois commented Jan 11, 2022

@pcameron-, thanks for the contribution. LGTM.

@Haplois Haplois merged commit c431ce4 into microsoft:main Jan 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants