Skip to content

Instantly share code, notes, and snippets.

@AlbertoMonteiro
Created May 15, 2021 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlbertoMonteiro/84d08f456b2f9e34f711d95f317e02a9 to your computer and use it in GitHub Desktop.
Save AlbertoMonteiro/84d08f456b2f9e34f711d95f317e02a9 to your computer and use it in GitHub Desktop.
Formatar Cpf benchmark
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.18363.1500 (1909/November2018Update/19H2)
Intel Core i7-8665U CPU 1.90GHz (Coffee Lake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=5.0.202
  [Host]     : .NET Core 5.0.5 (CoreCLR 5.0.521.16609, CoreFX 5.0.521.16609), X64 RyuJIT
  DefaultJob : .NET Core 5.0.5 (CoreCLR 5.0.521.16609, CoreFX 5.0.521.16609), X64 RyuJIT

Method Mean Error StdDev Ratio RatioSD Gen 0 Gen 1 Gen 2 Allocated
FormataComSpan 46.58 ns 0.843 ns 0.748 ns 0.35 0.01 0.0134 - - 56 B
FormataComSpanSlice 32.54 ns 0.621 ns 1.337 ns 0.25 0.01 0.0134 - - 56 B
FormataComIndexRange 131.05 ns 2.641 ns 2.470 ns 1.00 0.03 0.0591 - - 248 B
FormataComSubString 131.81 ns 2.256 ns 2.414 ns 1.00 0.00 0.0629 - - 264 B
using BenchmarkDotNet.Attributes;
using System;
namespace RemoveLater
{
[MemoryDiagnoser]
public class FormatarCpf
{
private string _cpf;
[GlobalSetup]
public void Setup()
{
_cpf = "12345678901";
}
[Benchmark]
public string FormataComSpan()
{
var cpfSpan = _cpf.AsSpan();
Span<char> cpfFormatado = stackalloc char[14];
cpfFormatado[3] = '.';
cpfFormatado[7] = '.';
cpfFormatado[11] = '-';
for (var i = (src: 0, dest: 0); i.src < 11;)
{
if (i.src == 3 || i.src == 6 || i.src == 9)
i.dest++;
cpfFormatado[i.dest] = cpfSpan[i.src];
i = (i.src + 1, i.dest + 1);
}
return cpfFormatado.ToString();
}
[Benchmark]
public string FormataComSpanSlice()
{
var cpfSpan = _cpf.AsSpan();
Span<char> cpfFormatado = stackalloc char[14];
cpfFormatado[3] = '.';
cpfFormatado[7] = '.';
cpfFormatado[11] = '-';
cpfSpan.Slice(0, 3).CopyTo(cpfFormatado.Slice(0, 3));
cpfSpan.Slice(3, 3).CopyTo(cpfFormatado.Slice(4, 3));
cpfSpan.Slice(6, 3).CopyTo(cpfFormatado.Slice(8, 3));
cpfSpan.Slice(9, 2).CopyTo(cpfFormatado.Slice(12, 2));
return cpfFormatado.ToString();
}
[Benchmark]
public string FormataComIndexRange()
{
return $"{_cpf[0..2]}.{_cpf[3..5]}.{_cpf[6..8]}-{_cpf[9..10]}";
}
[Benchmark(Baseline = true)]
public string FormataComSubString()
{
return $"{_cpf.Substring(0, 3)}.{_cpf.Substring(3, 3)}.{_cpf.Substring(6, 3)}-{_cpf.Substring(9, 2)}";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment