Reduces heap allocations for the some byte[] uses#1272
Reduces heap allocations for the some byte[] uses#1272WojciechNagorski merged 1 commit intosshnet:developfrom
Conversation
|
Funny, I had very similar changes in #1138 🙂 Feel free to cherry-pick some of those, or otherwise this looks good to me |
@Rob-Hague wow, your changes are more than a little similar. At one point I had even ported the Why didn't you ever merge this? |
|
I think I wanted to justify it with some profiling like you did, but got stuck into some other work |
|
I will merge any optimization if it has justify as goof as this PR 😃. #1138 was a draft. |
|
The 2023.0.1 version has been released to Nuget: https://www.nuget.org/packages/SSH.NET/2023.0.1 |
Profiling reveals that creation of
byte[4]arrays are our most common heap objects. Many of these come from reading integers from the byte stream where we allocate a smallbyte[4]orbyte[8]array and then convert it to a 32 or 64-bit integer.Results from a simple test of using the
SftpClientto upload and download some files:Before: when byte[] arrays were created for each integer read

After: when byte[] are allocated and read from the stack

Changes
SshDataStream.ReadBytesoverload that supportsSpan<byte>for .NET Standard 2.1+ and .NET 6+ targets.SshDataStream.ReadUInt32andSshDataStream.ReadUInt64to read onto the stack and use newerBinaryPrimitivesclass for integer conversion for .NET Standard 2.1+ and .NET 6+ targets.SshData.ReadUInt32andSshData.ReadUInt64to use the existing stream methods to avoid another temporary buffer.