Reputation: 3246
I have this condition:
If (cmbStatusSearch.SelectedValue <> "-1") Then
How can I make it better in performance? I read String.CompareOrdinal is faster in comparing strings. So should I use:
If (String.CompareOrdinal(cmbStatusSearch.SelectedValue,"-1" <>0) Then
Or is there any other way to make if faster in performance?
Upvotes: 1
Views: 1940
Reputation: 6821
Lets think about this:
Any string equality check can be implemented viastring.CompareOrdinal
.
A string comparison check cannot be implemented via an equality check.
So if CompareOrdinal
was faster, why wouldn't they just implement Equals
in terms of it? In fact it's slower (exact numbers depend on framework), but this is not surprising since it does strictly more work.
Upvotes: 0
Reputation: 96477
I think you're being overly concerned about the wrong type of performance issues and prematurely optimizing a trivial piece of code.
The first example is much more readable than the second. If it serves your purpose then move on and be content with it. Your performance bottleneck will not be in that statement. If you feel some operation in your program is slow then use a profiler, such as the ANTS Performance Profiler (or similar), to discover where the bottleneck is. Until then, guessing about performance issues is futile.
To put this into perspective, consider that no one would use LINQ if they were so concerned over performance to the level presented in your question. Instead, they would stick to traditional code and for loops, which are known to be faster. However, for the sake of readability and expressiveness, LINQ is commonly used and acceptable.
Although String.CompareOrdinal
might be more efficient, I would recommend using it when you need to benefit from its intended purpose, which is to perform a case-sensitive comparison using ordinal sort rules. Otherwise, for your posted example, a direct comparison is fine and more readable.
Upvotes: 3