The default implementation of Equal for strings is a reference comparison. C# internalizes strings for exactly this performance related reason. The following test confirms this, as there is only a minor difference between the two performance tests, where, if string matching were being performed, the two tests would very greatly in times (they do not).
Code:
using System;
using System.Collections;
using System.Collections.Generic;
//------------------------------------------------------------------------------
public class Test
{
private static int[,] m_Integers = new int[,]
{
{ 1, 3 },
{ 3, 3 },
{ 3, 5 },
{ 5, 5 },
{ 5, 7 },
{ 7, 7 },
{ 7, 11 },
{ 11, 11 },
{ 11, 13 },
{ 13, 13 },
};
private static string[,] m_Strings = new string[,]
{
{ "thisisaridculouslylongstring_one", "thisisaridculouslylongstring_three" },
{ "thisisaridculouslylongstring_three", "thisisaridculouslylongstring_three" },
{ "thisisaridculouslylongstring_three", "thisisaridculouslylongstring_five" },
{ "thisisaridculouslylongstring_five", "thisisaridculouslylongstring_five" },
{ "thisisaridculouslylongstring_five", "thisisaridculouslylongstring_seven" },
{ "thisisaridculouslylongstring_seven", "thisisaridculouslylongstring_seven" },
{ "thisisaridculouslylongstring_seven", "thisisaridculouslylongstring_eleven" },
{ "thisisaridculouslylongstring_eleven", "thisisaridculouslylongstring_eleven" },
{ "thisisaridculouslylongstring_eleven", "thisisaridculouslylongstring_thirteen" },
{ "thisisaridculouslylongstring_thirteen", "thisisaridculouslylongstring_thirteen" },
};
//------------------------------------------------------------------------------
public static void Main( string[] args )
{
{
double start = DateTime.Now.Ticks / 10000000.0;
long count = 0;
for( long i=0; i<100000000; i++)
{
int index = (int)( i % 10L );
if( m_Integers[index,0]==m_Integers[index,1] ) count++;
}
double stop = DateTime.Now.Ticks / 10000000.0;
double elapsed = stop - start;
Console.WriteLine("INTEGERS");
Console.WriteLine(" count: "+count);
Console.WriteLine(" elapsed: "+elapsed);
}
{
double start = DateTime.Now.Ticks / 10000000.0;
long count = 0;
for( long i=0; i<100000000; i++)
{
int index = (int)( i % 10L );
if( m_Strings[index,0]==m_Strings[index,1] ) count++;
}
double stop = DateTime.Now.Ticks / 10000000.0;
double elapsed = stop - start;
Console.WriteLine("STRINGS");
Console.WriteLine(" count: "+count);
Console.WriteLine(" elapsed: "+elapsed);
}
}
}
//------------------------------------------------------------------------------
On my computer, I (correctly) calculate 50,000,000 matches for each case, but case one takes 3.70 seconds, and case two takes 4.65. The difference in times is probably associated with the function dispatch, but then recouped by the reference (pointer address) compare. I should imagine that if Int were used instead of the primitive int, these tests would come out the
same.
C//