I am trying to improve performance on the following (sample) code.
Object[] inputKeys = new Object[10];
inputKeys[0] = "4021";
inputKeys[1] = "3011";
inputKeys[2] = "1010";
inputKeys[3] = "1020";
inputKeys[4] = "1030";
then the input keys are compared.
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
bool result = inputKeys[i].Equals(inputKeys[j]);
}
}
The inputKeys can be all of type string
, int32
or DateTime
.
There is a huge performance drop in .Equals
line, when it hits millions of times.
Any suggestions on how to improve performance of this line (the equality check)?
I have tried this: Using an array of below class instead of the Object array to hold the keys. There I keep the Key type and key values.
public class CustomKey : IEquatable<CustomKey>{
internal int KeyType { get; private set; }
internal string ValueString { get; private set; }
internal int ValueInteger { get; private set; }
internal DateTime ValueDateTime { get; private set; }
internal CustomKey(string keyValue)
{
this.KeyType = 0;
this.ValueString = (string)keyValue;
}
internal CustomKey(int keyValue)
{
this.KeyType = 1;
this.ValueInteger = (int)keyValue;
}
internal CustomKey(DateTime keyValue)
{
this.KeyType = 2;
this.ValueDateTime = (DateTime)keyValue;
}
public bool Equals(CustomKey other)
{
if (this.KeyType != other.KeyType)
{
return false;
}
else
{
if (this.KeyType == 0)
{
return this.ValueString.Equals(other.ValueString);
}
else if (this.KeyType == 1)
{
return this.ValueInteger.Equals(other.ValueInteger);
}
else if (this.KeyType == 2)
{
return this.ValueDateTime.Equals(other.ValueDateTime);
}
else
{
return false;
}
}
}
}
But the performance was worse.