Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# performance: type comparison vs. string comparison

Which is faster? This:

bool isEqual = (MyObject1 is MyObject2)

Or this:

bool isEqual = ("blah" == "blah1")

It would be helpful to figure out which one is faster. Obviously, if you apply .ToUpper() to each side of the string comparison like programmers often do, that would require reallocating memory which affects performance. But how about if .ToUpper() is out of the equation like in the above sample?

like image 294
user28661 Avatar asked Nov 15 '08 00:11

user28661


2 Answers

I'm a little confused here.

As other answers have noted, you're comparing apples and oranges. ::rimshot::

If you want to determine if an object is of a certain type use the is operator.

If you want to compare strings use the == operator (or other appropriate comparison method if you need something fancy like case-insensitive comparisons).

How fast one operation is compared to the other (no pun intended) doesn't seem to really matter.


After closer reading, I think that you want to compare the speed of string comparisions with the speed of reference comparisons (the type of comparison used in the System.Object base type).

If that's the case, then the answer is that reference comparisons will never be slower than any other string comparison. Reference comparison in .NET is pretty much analogous to comparing pointers in C - about as fast as you can get.

However, how would you feel if a string variable s had the value "I'm a string", but the following comparison failed:

if (((object) s) == ((object) "I'm a string")) { ... }

If you simply compared references, that might happen depending on how the value of s was created. If it ended up not being interned, it would not have the same reference as the literal string, so the comparison would fail. So you might have a faster comparison that didn't always work. That seems to be a bad optimization.

like image 60
Michael Burr Avatar answered Sep 19 '22 11:09

Michael Burr


According to the book Maximizing .NET Performance the call

bool isEqual = String.Equals("test", "test");

is identical in performance to

bool isEqual = ("test" == "test");

The call

bool isEqual = "test".Equals("test");

is theoretically slower than the call to the static String.Equals method, but I think you'll need to compare several million strings in order to actually detect a speed difference.

My tip to you is this; don't worry about which string comparison method is slower or faster. In a normal application you'll never ever notice the difference. You should use the way which you think is most readable.

like image 34
Frode Lillerud Avatar answered Sep 20 '22 11:09

Frode Lillerud