A revisit to a tiny C# shortcut
My blog on string.IsNullOrEmpty() caused quite a stir (in my micro-scale, anyway), I got a number of comments, most of them interesting, and I feel happy of *not* being the only guy interested in silly small details. The feedback forced me to polish my benchmark, first of all James Bogosian is right: the performance differences are really small, I had to do 20'000.000 and 30'000.000 comparisons to see some stable differences. I also introduced the name.Length > 0 comparison out of several suggestions; after some cleaning, the results for the not null and not empty string tests were these:
.Length > 0 | 80 ms |
string.IsNullOrEmpty() | 110 ms |
!= "" | 270 ms |
!= string.Empty | 440 ms |
And, surprise Edgar, name.Length > 0 is the best so Ramon Smits and other guys get a point here. The other unexpected result is that comparing to string.Empty is a real bummer, so Darren Kopp suggestion is not really good (but he also supported the use of the Length property, so you're just OK, Darren). Someone suggested that comparing with "" is bad because a lot of string objects are generated, Ildasm shows that a ldstr "" instruction is generated just before the comparison, and although I'm far from an IL expert, I suspect no extra strings are being instantiated. Personally, I will stick to string.IsNullOrEmpty() because, as James pointed out, it's not only a matter of performance but of readability (or perhaps I am just rationalizing my bad habits ;-) ). You can download the test class from here, try it, mangle it, feedback me.