From 0f2a76bd5e9ea359bcc3b84c079f8d4de6e94b72 Mon Sep 17 00:00:00 2001 From: Morilli <35152647+Morilli@users.noreply.github.com> Date: Sun, 16 Apr 2023 15:33:40 +0200 Subject: [PATCH] lazy-initialize zstd contexts to reduce alloations This becomes mostly apparent in the PlayMovie dialog where one zstd instance is created for every single movie, churning significant amounts of memory even though zstd isn't even used --- src/BizHawk.Emulation.Common/zstd/Zstd.cs | 40 ++++++++++------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/src/BizHawk.Emulation.Common/zstd/Zstd.cs b/src/BizHawk.Emulation.Common/zstd/Zstd.cs index 8330903f89..4015e7c110 100644 --- a/src/BizHawk.Emulation.Common/zstd/Zstd.cs +++ b/src/BizHawk.Emulation.Common/zstd/Zstd.cs @@ -1,13 +1,13 @@ -using System; -using System.IO; -using System.Runtime.InteropServices; - -using BizHawk.BizInvoke; -using BizHawk.Common; - -namespace BizHawk.Emulation.Common -{ - public sealed class Zstd : IDisposable +using System; +using System.IO; +using System.Runtime.InteropServices; + +using BizHawk.BizInvoke; +using BizHawk.Common; + +namespace BizHawk.Emulation.Common +{ + public sealed class Zstd : IDisposable { private sealed class ZstdCompressionStreamContext : IDisposable { @@ -380,14 +380,8 @@ namespace BizHawk.Emulation.Common MaxCompressionLevel = _lib.ZSTD_maxCLevel(); } - private readonly ZstdCompressionStreamContext _compressionStreamContext; - private readonly ZstdDecompressionStreamContext _decompressionStreamContext; - - public Zstd() - { - _compressionStreamContext = new(); - _decompressionStreamContext = new(); - } + private ZstdCompressionStreamContext? _compressionStreamContext; + private ZstdDecompressionStreamContext? _decompressionStreamContext; private bool _disposed = false; @@ -395,8 +389,8 @@ namespace BizHawk.Emulation.Common { if (!_disposed) { - _compressionStreamContext.Dispose(); - _decompressionStreamContext.Dispose(); + _compressionStreamContext?.Dispose(); + _decompressionStreamContext?.Dispose(); _disposed = true; } } @@ -429,6 +423,7 @@ namespace BizHawk.Emulation.Common throw new ArgumentOutOfRangeException(nameof(compressionLevel)); } + _compressionStreamContext ??= new(); _compressionStreamContext.InitContext(compressionLevel); return new ZstdCompressionStream(stream, _compressionStreamContext); } @@ -446,6 +441,7 @@ namespace BizHawk.Emulation.Common /// zstd decompression stream public Stream CreateZstdDecompressionStream(Stream stream) { + _decompressionStreamContext ??= new(); _decompressionStreamContext.InitContext(); return new ZstdDecompressionStream(stream, _decompressionStreamContext); } @@ -480,5 +476,5 @@ namespace BizHawk.Emulation.Common dstream.CopyTo(ret); return ret; } - } -} + } +}