From 152ee810383705be3fda5ace36432bd3098107f0 Mon Sep 17 00:00:00 2001 From: Stanley Dimant Date: Mon, 4 Nov 2024 21:20:40 +0100 Subject: [PATCH] adjust stream buffersize based on file size --- .../Utils/BlockFileDataSubstream.cs | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/MareSynchronosServer/MareSynchronosStaticFilesServer/Utils/BlockFileDataSubstream.cs b/MareSynchronosServer/MareSynchronosStaticFilesServer/Utils/BlockFileDataSubstream.cs index 6f0169a..a1d98e2 100644 --- a/MareSynchronosServer/MareSynchronosStaticFilesServer/Utils/BlockFileDataSubstream.cs +++ b/MareSynchronosServer/MareSynchronosStaticFilesServer/Utils/BlockFileDataSubstream.cs @@ -12,10 +12,33 @@ public sealed class BlockFileDataSubstream : IDisposable public BlockFileDataSubstream(FileInfo file) { - _dataStreamLazy = new(() => File.Open(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Inheritable)); + _dataStreamLazy = new(() => File.Open(file.FullName, GetFileStreamOptions(file.Length))); _headerStream = new MemoryStream(Encoding.ASCII.GetBytes("#" + file.Name + ":" + file.Length.ToString(CultureInfo.InvariantCulture) + "#")); } + private static FileStreamOptions GetFileStreamOptions(long fileSize) + { + int bufferSize = fileSize switch + { + <= 128 * 1024 => 0, + <= 512 * 1024 => 4096, + <= 1 * 1024 * 1024 => 65536, + <= 10 * 1024 * 1024 => 131072, + <= 100 * 1024 * 1024 => 524288, + _ => 1048576 + }; + + FileStreamOptions opts = new() + { + Mode = FileMode.Open, + Access = FileAccess.Read, + Share = FileShare.Read | FileShare.Inheritable, + BufferSize = bufferSize + }; + + return opts; + } + public int Read(byte[] inputBuffer, int offset, int count) { int bytesRead = 0;