I am implementing my collection:
SpecialCollection class:
public class SpecialCollection<TId, TName, TValue> : Dictionary<CompositeKey<TId, TName>, TValue>
{
#region Private fileds
private Dictionary<CompositeKey<TId, TName>, TValue> _baseDictionary = null;
private ReaderWriterLockSlim _readWriteLockSlim = new ReaderWriterLockSlim();
#endregion
#region Constructors
public SpecialCollection()
{
_baseDictionary = new Dictionary<CompositeKey<TId, TName>, TValue>();
}
#endregion
public void Add(CompositeKey<TId, TName> compositeKey, TValue value)
{
_readWriteLockSlim.EnterWriteLock();
try
{
_baseDictionary.Add(compositeKey, value);
}
catch (ArgumentNullException ex)
{
throw ex;
}
catch (ArgumentException ex)
{
throw ex;
}
finally
{
_readWriteLockSlim.ExitWriteLock();
}
}
}
CompositeKey class:
public struct CompositeKey<TId, TName> : IEquatable<Tuple<TId, TName>>
{
public TId Id;
public TName Name;
public CompositeKey(TId id, TName name)
{
Id = id;
Name = name;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (this.GetType() != obj.GetType())
return false;
return AreEqual(this, (CompositeKey<TId, TName>)obj);
}
public bool Equals(CompositeKey<TId, TName> other)
{
return AreEqual(this, other);
}
private static bool AreEqual(CompositeKey<TId, TName> a, CompositeKey<TId, TName> b)
{
if (!a.Id.Equals(b.Id))
return false;
if (!a.Name.Equals(b.Name))
return false;
return true;
}
public static bool operator == (CompositeKey<TId, TName> a, CompositeKey<TId, TName> b)
{
return AreEqual(a, b);
}
public static bool operator != (CompositeKey<TId, TName> a, CompositeKey<TId, TName> b)
{
return !AreEqual(a, b);
}
public override int GetHashCode()
{
return Id.GetHashCode() ^ Name.GetHashCode();
}
public bool Equals(Tuple<TId, TName> other)
{
throw new NotImplementedException();
}
}
I faced with a question related to performance. For example, the adding of 10000 elements to my collection takes 9745
milliseconds. But the adding of 10000 elements to ConcurrentDictionary takes 4965
milliseconds.
If add 30000 elements to my collection, it takes a lot of time - about 40000
milliseconds.
I have no idea how to improve the performance :( Could you please to tell how can I improve the performance of my collection if it is possible? May be, the performance related to CompositeKey class?
Edit:
I tested the performance like this:
ConcurrentDictionary<CompositeKey<int, int>, int> cd = new ConcurrentDictionary<CompositeKey<int, int>, int>();
SpecialCollection<int, int, int> sc = new SpecialCollection<int, int, int>();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000; i++)
{
cd.TryAdd(new CompositeKey<int, int>(i, i), i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
sw.Start();
for (int i = 0; i < 10000; i++)
{
sc.Add(new CompositeKey<int, int>(i, i), i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Thanks!