-
Notifications
You must be signed in to change notification settings - Fork 269
/
StringSegmentBenchmark.cs
92 lines (71 loc) · 3 KB
/
StringSegmentBenchmark.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using MicroBenchmarks;
namespace Microsoft.Extensions.Primitives
{
[BenchmarkCategory(Categories.Libraries)]
public class StringSegmentBenchmark
{
private readonly StringSegment _segment = new StringSegment("Hello world!");
private readonly StringSegment _segment2 = new StringSegment("Hello world!".AsSpan().ToString()); // different backing string instance
private readonly StringSegment _largeSegment = new StringSegment("Hello, World!, Hello people! My Car Is Cool. Your Carport is blue.");
private readonly StringSegment _trimSegment = new StringSegment(" Hello world! ");
private readonly object _boxedSegment;
private readonly char[] _indexOfAnyChars = { 'w', 'l' };
public StringSegmentBenchmark()
{
_boxedSegment = _segment;
}
[Benchmark]
public StringSegment Ctor_String() => new StringSegment("Hello world!");
[Benchmark]
public string GetValue() => _segment.Value;
[Benchmark]
public char Indexer()
{
var segment = _segment;
char result = default;
for (int i = 0; i < segment.Length; i++)
{
result ^= segment[i];
}
return result;
}
[Benchmark]
public bool Equals_Object_Invalid() => _segment.Equals(null as object);
[Benchmark]
[MemoryRandomization]
public bool Equals_Object_Valid() => _segment2.Equals(_boxedSegment);
[Benchmark]
[MemoryRandomization]
public bool Equals_Valid() => _segment2.Equals(_segment);
[Benchmark]
public bool Equals_String() => _segment2.Equals("Hello world!");
[Benchmark]
public int GetSegmentHashCode() => _segment.GetHashCode();
[Benchmark]
public bool StartsWith() => _largeSegment.StartsWith("Hel", StringComparison.Ordinal);
[Benchmark]
public bool EndsWith() => _largeSegment.EndsWith("ld!", StringComparison.Ordinal);
[Benchmark]
public string SubString() => _segment.Substring(3, 2);
[Benchmark]
public StringSegment SubSegment() => _segment.Subsegment(3, 2);
[Benchmark]
public int IndexOf() => _largeSegment.IndexOf(' ', 1, 7);
[Benchmark]
public int IndexOfAny() => _largeSegment.IndexOfAny(_indexOfAnyChars, 1, 7);
[Benchmark]
public int LastIndexOf() => _largeSegment.LastIndexOf('l');
[Benchmark]
public StringSegment Trim() => _trimSegment.Trim();
[Benchmark]
public StringSegment TrimStart() => _trimSegment.TrimStart();
[Benchmark]
public StringSegment TrimEnd() => _trimSegment.TrimEnd();
}
}