Last active
February 3, 2022 16:06
-
-
Save mjebrahimi/83d99906458eb9d7414c5c95dc20fb97 to your computer and use it in GitHub Desktop.
High Performance Generic Type Dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ----------------------------------------------------------------------- | |
// <copyright file="TypedDictionary.cs" company="Asynkron AB"> | |
// Copyright (C) 2015-2021 Asynkron AB All rights reserved | |
// </copyright> | |
// ----------------------------------------------------------------------- | |
using System; | |
using System.Threading; | |
namespace Proto.Utils | |
{ | |
public class TypeDictionary<TValue> | |
{ | |
// ReSharper disable once StaticMemberInGenericType | |
private static int typeIndex; | |
private readonly object _lockObject = new(); | |
private TValue[] _values = new TValue[100]; | |
public void Add<TKey>(TValue value) | |
{ | |
lock (_lockObject) | |
{ | |
var id = TypeKey<TKey>.Id; | |
if (id >= _values.Length) Array.Resize(ref _values, id * 2); | |
_values[id] = value; | |
} | |
} | |
public TValue? Get<TKey>() | |
{ | |
var id = TypeKey<TKey>.Id; | |
return id >= _values.Length ? default : _values[id]; | |
} | |
// ReSharper disable once UnusedTypeParameter | |
private static class TypeKey<TKey> | |
{ | |
// ReSharper disable once StaticMemberInGenericType | |
internal static readonly int Id = Interlocked.Increment(ref typeIndex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original: https://github.com/asynkron/protoactor-dotnet/blob/dev/src/Proto.Actor/Utils/TypedDictionary.cs