Skip to content

Instantly share code, notes, and snippets.

@fjod
Last active July 6, 2022 10:19
Show Gist options
  • Save fjod/b5a7a6d0aea90c5755146aee22fa63e4 to your computer and use it in GitHub Desktop.
Save fjod/b5a7a6d0aea90c5755146aee22fa63e4 to your computer and use it in GitHub Desktop.
image from memoryStream to base64 with little allocations
using System.Buffers;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using ConverterTest;
namespace MyBenchmarks
{
public class Program
{
public static void Main(string[] args)
{
var q = new Test();
q.Array();
q.Spans();
q.ArraysRent();
var summary = BenchmarkRunner.Run(typeof(Program).Assembly);
}
}
}
using System.Buffers;
using BenchmarkDotNet.Attributes;
namespace ConverterTest;
[MemoryDiagnoser(true)]
public class Test
{
private readonly MemoryStream _stream;
public Test()
{
using var fileStream = new FileStream("F:\\nipi\\kiuss\\src\\Dt.Kpsirs.ClientGateway\\bin\\Debug\\net6.0\\files\\bd\\bd84b2df-eea9-46bf-9571-99a8ebd08f72__", FileMode.Open, FileAccess.Read);
_stream = new MemoryStream();
fileStream.CopyTo(_stream);
_stream.Seek(0, SeekOrigin.Begin);
}
[Benchmark]
public string Spans()
{
_stream.Position = 0;
Span<byte> numbers = stackalloc byte[_stream.Capacity];
_stream.Read(numbers);
return Convert.ToBase64String(numbers);
}
ArrayPool<byte> shared = ArrayPool<byte>.Shared;
[Benchmark]
public string ArraysRent()
{
_stream.Position = 0;
var rentedArray = shared.Rent(_stream.Capacity);
_stream.Read(rentedArray);
var result = Convert.ToBase64String(rentedArray);
shared.Return(rentedArray, true);
return result;
}
[Benchmark]
public string Array()
{
_stream.Position = 0;
var result = Convert.ToBase64String(_stream.ToArray());
return result;
}
}
@fjod
Copy link
Author

fjod commented Jul 6, 2022

image

@fjod
Copy link
Author

fjod commented Jul 6, 2022

I guess it's bad example for arrayRent, it needs to be tested with processing several different size files in a row.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment