2

I am trying to use ReadOnlySpan<T>, for decoding purpose. (here is initial question). Regarding Microsoft documentation, I may find it in System.Runtime.dll

I checked and foud it in folder C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\Facades, but I still cannot use ReadOnlySpan.

Project is in .NET Framework 4.8

Is there something I am missing? Thanks

Siegfried.V
  • 1,508
  • 1
  • 16
  • 34
  • 2
    `Span` was introduced in .NET Core 2.1, see [this table](https://learn.microsoft.com/en-us/dotnet/api/system.span-1?view=net-6.0#applies-to). You can use it in .NET Framework by referencing the [System.Memory NuGet package](https://www.nuget.org/packages/System.Memory/). Note however that this doesn't bring you quite the same speed improvements as using .NET Core 2.1+ – canton7 Jan 21 '22 at 14:58
  • @canton7 and how can I do it without the nuget?(as I understood, the nuget will impact the performances or something like that?) I am pretty new to all that, I need to decode some strange strings, and after I would like also to encode. But to be honnest the code given by xanatos is... I just don't understand how it works, and wanted to make some tests to understand that. – Siegfried.V Jan 21 '22 at 15:01
  • You don't - the type is not available on .NET Framework, so the only way to use it is by referencing that nuget package. Nuget packages don't impact performance though. However, that answer only uses a single span, and you can just replace the line `ReadOnlySpan bytes = stackalloc byte[] { (byte)(ch3 + 128) };` with `byte[] bytes = new byte[] { (byte)(ch3 + 128) }` -- it allocates slightly more, but you won't notice – canton7 Jan 21 '22 at 15:04
  • @canton7 thanks, in fact, replaced `ReadOnlySpan bytes = stackalloc byte[] { (byte)(ch3 + 128) }` by `var bytes = new byte[] { (byte)(ch3 + 128) };` and that solved the problem very well. Thanks, if you may put that as answer, I'd close the question. – Siegfried.V Jan 21 '22 at 15:09

1 Answers1

1

Span<T> (and ReadOnlySpan<T>) were introduced in .NET Core 2.1, see this table. You can use it in .NET Framework by referencing the System.Memory NuGet package. Note however that this doesn't bring you quite the same speed improvements as using .NET Core 2.1+.

However, the code you're trying to use only has a single use of a span:

ReadOnlySpan<byte> bytes = stackalloc byte[] { (byte)(ch3 + 128) };

This is a cheap way to allocate an array on the stack, avoiding an object allocation. It's probably easier for you to just allocate an array here: with all of the other object allocations going on in that code, you won't notice the additional small cost:

byte[] bytes = new byte[] { (byte)(ch3 + 128) };
canton7
  • 37,633
  • 3
  • 64
  • 77