I decided to give it a try and created the following code:
Stopwatch watch = new Stopwatch();
string str1 = "MyTest";
string str2 = str1.Substring(0,2)+"Test";
watch.Start();
if(str1 == str2)
{
Console.WriteLine("str1 == str2");
}
watch.Stop();
Console.WriteLine(watch.Elapsed);
watch.Restart();
var obj1 = (object)str1;
var obj2 = (object)str2;
if(obj1 == obj2)
{
Console.WriteLine("obj1 == obj2");
}
watch.Stop();
Console.WriteLine(watch.Elapsed);
string str3 = "MyTest";
string str4 = "MyTest";
watch.Restart();
if (str3 == str4)
{
Console.WriteLine("str3 == str4");
}
watch.Stop();
Console.WriteLine(watch.Elapsed);
watch.Restart();
watch.Restart();
var obj3 = (object)str3;
var obj4 = (object)str4;
if (obj3 == obj4)
{
Console.WriteLine("obj3 == obj4");
}
watch.Stop();
Console.WriteLine(watch.Elapsed);
if (true)
{
Console.WriteLine("true");
}
watch.Stop();
Console.WriteLine(watch.Elapsed);
it yielded the following result:
//str1 == str2
//00:00:00.0564061
//00:00:00.0000116
//str3 == str4
//00:00:00.0103047
//obj3 == obj4
//00:00:00.0000004
//true
//00:00:00.0000004
my two cents on the matter - by default, strings, if they are "hardcoded" are interned by the system, so str3 and str4 reference the same string. However, comparing two strings is always by value, so it actually has to run across the entire string.
However, if the strings are interned (hold the same reference) and you convert them to an object it forces a by ref comperison - and that forces it to become a non costly operation, and actually have the same performence as checking a boolean.
** there should be an overhead of converting to object, but according to my tests, it seems unnoticable.
As for your question
obviously, checking a string is far more costly than checking a boolean, and is determined by the length of the strings, and how similar they are. So, using a string is not a good choice.
However
If you do use strings for checking equality - you should probably make sure they hold the same reference (str = str2
is an example) and check equality by ref.
(all of this is not really noticable, but still)