Why is this an issue?
With string.StartsWith(char)
and string.EndsWith(char)
, only the first character of the string is compared to the
provided character, whereas the string
versions of those methods have to do checks about the current StringComparison
and
CultureInfo
. Thus, the char
overloads are significantly faster for default comparison scenarios.
These overloads were introduced in .NET Core 2.0
.
What is the potential impact?
We measured at least 3.5x improvement in execution time. For more details see the Benchmarks
section from the More info
tab.
How to fix it
If you are targeting a runtime version equal or greater than .NET Core 2.0
, the string.StartsWith
and
string.EndsWith
overloads are available, with the argument’s type being char
instead of string
. Thus, an
argument of char
type can be provided.
Code examples
Noncompliant code example
bool StartsWithSlash(string s) =>
s.StartsWith("/");
bool EndsWithSlash(string s) =>
s.EndsWith("/");
Compliant solution
bool StartsWithSlash(string s) =>
s.StartsWith('/');
bool EndsWithSlash(string s) =>
s.EndsWith('/');
Resources
Documentation
Benchmarks
Method |
Mean |
StdDev |
Median |
StartsWith_String |
30.965 ms |
3.2732 ms |
29.932 ms |
StartsWith_Char |
7.568 ms |
0.3235 ms |
7.534 ms |
EndsWith_String |
30.421 ms |
5.1136 ms |
28.101 ms |
EndsWith_Char |
8.067 ms |
0.7092 ms |
7.935 ms |
The results were generated by running the following snippet with BenchmarkDotNet:
private List<string> data;
[Params(1_000_000)]
public int N { get; set; }
[GlobalSetup]
public void Setup() =>
data = Enumerable.Range(0, N).Select(_ => Guid.NewGuid().ToString()).ToList();
[Benchmark]
public void StartsWith_String()
{
_ = data.Where(guid => guid.StartsWith("d")).ToList();
}
[Benchmark]
public void StartsWith_Char()
{
_ = data.Where(guid => guid.StartsWith('d')).ToList();
}
[Benchmark]
public void EndsWith_String()
{
_ = data.Where(guid => guid.EndsWith("d")).ToList();
}
[Benchmark]
public void EndsWith_Char()
{
_ = data.Where(guid => guid.EndsWith('d')).ToList();
}
Hardware configuration:
BenchmarkDotNet=v0.13.5, OS=Windows 10 (10.0.19045.2846/22H2/2022Update)
11th Gen Intel Core i7-11850H 2.50GHz, 1 CPU, 16 logical and 8 physical cores
.NET SDK=7.0.203
[Host] : .NET 7.0.5 (7.0.523.17405), X64 RyuJIT AVX2
.NET 7.0 : .NET 7.0.5 (7.0.523.17405), X64 RyuJIT AVX2