/
FileOpenTextCharIndexOfAnyBenchmark.cs
65 lines (55 loc) · 1.77 KB
/
FileOpenTextCharIndexOfAnyBenchmark.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
using System.Buffers;
using BenchmarkData;
namespace FileOpenTextCharIndexOfAnyBenchmark;
public static class FileOpenTextCharIndexOfAnyBenchmark
{
public static Count Count(string path)
{
long wordCount = 0, lineCount = 0, charCount = 0;
bool wasSpace = true;
char[] buffer = ArrayPool<char>.Shared.Rent(BenchmarkValues.Size);
using StreamReader reader = File.OpenText(path);
int count = 0;
while ((count = reader.Read(buffer)) > 0)
{
charCount += count;
Span<char> chars = buffer.AsSpan(0, count);
while (chars.Length > 0)
{
if (char.IsWhiteSpace(chars[0]))
{
if (chars[0] is '\n')
{
lineCount++;
}
wasSpace = true;
chars = chars.Slice(1);
continue;
}
else if (wasSpace)
{
wordCount++;
wasSpace = false;
chars = chars.Slice(1);
}
int index = chars.IndexOfAny(BenchmarkValues.WhitespaceValues);
if (index > -1)
{
if (chars[index] is '\n')
{
lineCount++;
}
wasSpace = true;
chars = chars.Slice(index + 1);
}
else
{
wasSpace = false;
chars = [];
}
}
}
ArrayPool<char>.Shared.Return(buffer);
return new(lineCount, wordCount, charCount, path);
}
}