简体   繁体   中英

String Comparison

Scenario

Consider the following code snippet.

        string s = "S";
        string s1 = "S";
        string s2 = string.Empty;
        switch (s)
        {
            case "S":
                s1 = "StringComparison";
                break;
            default:
                break;
        }

        switch (s[0])
        {
            case'S':
                s2 = "StringCOmpare2";
                break;
            default:
                break;
        }

the first switch case, results in a stringcomparison within IL.

But the second switch case, does not result in a stringcomparison within IL.

Can anyone justify this?

因为在第二个开关上您没有进行字符串比较,所以您在进行字符比较。

The easiest answer is that you're not doing a string comparison in the second block; you're comparing two characters.

However, you're right in that the two code blocks are functionally equivalent. A good optimizing compiler should be able to detect that 's' is a fixed-length string, and rewrite it not to use a full string comparison.

Your second switch statement isn't using a string , but a single char . Hence, no string comparison.

You're accessing the string via its indexer which returns a char and so lets you use the string as if it was an array of chars.

So whar you're doing is a char comparison. Using the apostrophe for the 'S' also tells you that you're using 'S' as a char and not as a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM