Skip to content

Commit

Permalink
Optimize file access
Browse files Browse the repository at this point in the history
Don't read the whole file into a string just to deserialize it into an object. Instead, just deserialize directly from the file stream.
  • Loading branch information
eerhardt committed Apr 5, 2022
1 parent a3ff856 commit 681d23f
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions src/MonkeyCache.FileStore/Barrel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ public IEnumerable<string> GetKeys(CacheState state = CacheState.Active)
}
}

T Get<T>(string key, Func<string, T> deserialize)
T Get<T>(string key, Func<FileStream, T> deserialize)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException("Key can not be null or empty.", nameof(key));
Expand All @@ -301,14 +301,13 @@ T Get<T>(string key, Func<string, T> deserialize)

if (index.ContainsKey(key) && File.Exists(path) && (!AutoExpire || (AutoExpire && !IsExpired(key))))
{
var contents = File.ReadAllText(path);
if (BarrelUtils.IsString(result))
{
object final = contents;
return (T)final;
return (T)(object)File.ReadAllText(path);
}

result = deserialize(contents);
using FileStream fileStream = new(path, FileMode.Open, FileAccess.Read);
result = deserialize(fileStream);
}
}
finally
Expand All @@ -322,15 +321,15 @@ T Get<T>(string key, Func<string, T> deserialize)
/// <inheritdoc/>
[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo, or make sure all of the required types are preserved.")]
public T Get<T>(string key, JsonSerializerOptions options = null) =>
Get(key, contents => JsonDeserialize<T>(contents, options));
Get(key, fileStream => JsonDeserialize<T>(fileStream, options));

[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Workaround https://github.com/dotnet/linker/issues/2001")]
static T JsonDeserialize<T>(string contents, JsonSerializerOptions options) =>
JsonSerializer.Deserialize<T>(contents, options);
static T JsonDeserialize<T>(FileStream fileStream, JsonSerializerOptions options) =>
JsonSerializer.Deserialize<T>(fileStream, options);

/// <inheritdoc/>
public T Get<T>(string key, JsonTypeInfo<T> jsonTypeInfo) => Get(key, contents =>
JsonSerializer.Deserialize(contents, jsonTypeInfo));
public T Get<T>(string key, JsonTypeInfo<T> jsonTypeInfo) => Get(key, fileStream =>
JsonSerializer.Deserialize(fileStream, jsonTypeInfo));

/// <summary>
/// Gets the DateTime that the item will expire for the specified key.
Expand Down

0 comments on commit 681d23f

Please sign in to comment.