Created
July 18, 2018 19:54
-
-
Save Tornhoof/95ab25ebd3217d573194d899e63e8a7e to your computer and use it in GitHub Desktop.
stringcreate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Runtime.CompilerServices; | |
using System.Runtime.InteropServices; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Attributes.Jobs; | |
using BenchmarkDotNet.Running; | |
using Newtonsoft.Json; | |
namespace ConsoleApp34 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<StringCreate>(); | |
} | |
} | |
[DisassemblyDiagnoser()] | |
[MemoryDiagnoser] | |
[ShortRunJob] | |
public class StringCreate | |
{ | |
[Params('H')] public char Symbol1; | |
[Params('i')] public char Symbol2; | |
[Benchmark] | |
public string ToString_Create() | |
{ | |
return string.Create(2, (Symbol1, Symbol2), (span, state) => | |
{ | |
span[1] = state.Symbol2; | |
span[0] = state.Symbol1; | |
}); | |
} | |
[Benchmark(Baseline = true)] | |
public unsafe string ToString_SuperStack() | |
{ | |
uint tmp = 0; | |
char* array = (char*) &tmp; | |
array[0] = Symbol1; | |
array[1] = Symbol2; | |
return new string(array,0,2); | |
} | |
[Benchmark] | |
public string ToString_Zero() | |
{ | |
var s = new string('\0',2); | |
var span = MemoryMarshal.CreateSpan(ref MemoryMarshal.GetReference(s.AsSpan()), 2); | |
span[1] = Symbol2; | |
span[0] = Symbol1; | |
return s; | |
} | |
} | |
} | |
``` ini | |
BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17134 | |
Intel Core i7-4790K CPU 4.00GHz (Haswell), 1 CPU, 8 logical and 4 physical cores | |
Frequency=3906256 Hz, Resolution=255.9996 ns, Timer=TSC | |
.NET Core SDK=2.1.400-preview-009063 | |
[Host] : .NET Core 2.1.1 (CoreCLR 4.6.26606.02, CoreFX 4.6.26606.05), 64bit RyuJIT | |
ShortRun : .NET Core 2.1.1 (CoreCLR 4.6.26606.02, CoreFX 4.6.26606.05), 64bit RyuJIT | |
Job=ShortRun LaunchCount=1 TargetCount=3 | |
WarmupCount=3 | |
``` | |
| Method | Symbol1 | Symbol2 | Mean | Error | StdDev | Scaled | Gen 0 | Allocated | | |
|-------------------- |-------- |-------- |---------:|----------:|----------:|-------:|-------:|----------:| | |
| ToString_Create | H | i | 9.441 ns | 0.3227 ns | 0.0182 ns | 1.18 | 0.0076 | 32 B | | |
| ToString_SuperStack | H | i | 8.008 ns | 0.0774 ns | 0.0044 ns | 1.00 | 0.0076 | 32 B | | |
| ToString_Zero | H | i | 5.889 ns | 0.6160 ns | 0.0348 ns | 0.74 | 0.0076 | 32 B | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment