Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to parse int from string using ReadOnlySpan<char>

Tags:

c#

While parsing int data from string, is there a way to use ReadOnlySpan<char> ? like int.Parse(str.AsSpan().Slice(2,3))

Because if the int data is in the middle of a string, like "Humans have 206 bones", then I have to make a substring first and then pass it to int.Parse(). Use of Span seems logical in this case.

like image 745
Muzib Avatar asked Mar 04 '23 00:03

Muzib


1 Answers

Yes, it is possible (I used .NET Core 3.0):

var text = "Humans have 206 bones";
ReadOnlySpan<char> asSpan = text.AsSpan();
var number = int.Parse(asSpan.Slice(12, 3));

I did some checks with BenchmarkDotNet, parsing an int from a string takes about 60-80% of the time via this code vs SubString.

|          Method |       N |             Mean |           Error |          StdDev | Ratio |
|---------------- |-------- |-----------------:|----------------:|----------------:|------:|
|       Substring |       1 |         31.14 ns |       0.0422 ns |       0.0374 ns |  1.00 |
| AsSpanThenSlice |       1 |         25.34 ns |       0.0519 ns |       0.0485 ns |  0.81 |
|     AsSpanInOne |       1 |         19.51 ns |       0.0544 ns |       0.0425 ns |  0.63 |
|                 |         |                  |                 |                 |       |
|       Substring |    1000 |     31,662.81 ns |      48.0289 ns |      44.9262 ns |  1.00 |
| AsSpanThenSlice |    1000 |     25,715.43 ns |      20.8666 ns |      17.4245 ns |  0.81 |
|     AsSpanInOne |    1000 |     18,344.96 ns |      15.3018 ns |      12.7777 ns |  0.58 |
|                 |         |                  |                 |                 |       |
|       Substring | 1000000 | 68,811,376.67 ns | 135,815.2457 ns | 127,041.6651 ns |  1.00 |
| AsSpanThenSlice | 1000000 | 44,843,871.11 ns |  97,723.9653 ns |  91,411.0578 ns |  0.65 |
|     AsSpanInOne | 1000000 | 38,622,410.65 ns |  27,490.1451 ns |  22,955.5162 ns |  0.56 |
like image 61
Peter Wishart Avatar answered May 06 '23 04:05

Peter Wishart