MetacoSA / NBitcoin

Comprehensive Bitcoin library for the .NET framework.
MIT License
1.87k stars 846 forks source link

Slightly faster `HexEncoder.EncodeData` for .NET 6 #1149

Closed kiminuo closed 1 year ago

kiminuo commented 1 year ago

Master branch (20965133)

dotnet run -c Release --framework net6.0 -- --runtimes net6.0 --filter *HexBench*
| Method |     Mean |    Error |   StdDev |
|------- |---------:|---------:|---------:|
| Decode | 55.94 ns | 0.445 ns | 0.395 ns |
| Encode | 82.44 ns | 0.872 ns | 0.816 ns |

Master + the PR's first commit (bd2e61b1)

dotnet run -c Release --framework net6.0 -- --runtimes net6.0 --filter *HexBench*
| Method |     Mean |    Error |   StdDev |
|------- |---------:|---------:|---------:|
| Decode | 56.14 ns | 0.385 ns | 0.341 ns |
| Encode | 30.02 ns | 0.499 ns | 0.467 ns |

Encode is about 2.5 times faster. The reason why it is so fast is because .NET uses a vectorized implementation for HEX encoding.

The issue with this commit is that the resulting hexadecimal strings are capitalized. Please upvote https://github.com/dotnet/runtime/issues/58937, https://github.com/dotnet/runtime/issues/73026, and https://github.com/dotnet/runtime/issues/60393 if you like.

This PR (bc496179)

dotnet run -c Release --framework net6.0 -- --runtimes net6.0 --filter *HexBench*
| Method |     Mean |    Error |   StdDev |
|------- |---------:|---------:|---------:|
| Decode | 54.68 ns | 0.530 ns | 0.470 ns |
| Encode | 68.04 ns | 1.005 ns | 0.940 ns |

Encode is about 1.2 times faster.

Resources

NicolasDorier commented 1 year ago

Sorry for taking long looking at that

NicolasDorier commented 1 year ago

Note that this PR because of not supporting lowercase is allocating way more.

kiminuo commented 1 year ago

Note that this PR because of not supporting lowercase is allocating way more.

Yes. Unfortunately, it's true but there is no way out of this. It's a bit bad luck that NBitcoin picked it one way and .NET the other way. But hopefully, they'll address it soon. Please upvote the issues if you can.