Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. C# String Comparison Tests

C# String Comparison Tests

Scheduled Pinned Locked Moved C#
questioncsharpperformancehelptutorial
18 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Kevin Marois

    I was just reading someone's blog where he tested

    bool isEmpty = (MyString == "");

    // also

    bool isEmpty = string.IsNullOrEmpty(MyString);

    // also

    bool isEmpty = string.IsNullOrWhiteSpace(MyString);

    // also

    bool isEmpty = MyString.Equals("");

    // also

    bool isEmpty = MyString.Length == 0;

    and he listed the number of ticks each example took. That got me thinking.... If you wanted to know of a string was null, that's one thing, and determining if its an empty string is another. But do you REALLY care about TICKS??? With today's PC's and Servers running at ultra high speed, why would anyone really care? Bonus question: I prefer IsNullOrWhiteSpace. What's your favorite & why?

    If it's not broken, fix it until it is

    G Offline
    G Offline
    Gyana_Ranjan Dash
    wrote on last edited by
    #4

    All are different functions but doing almost same work.So my choice better to use IsNullOrEmpty() as its safe and performance is good as compare to IsNullOrWhiteSpace().As IsNullOrWhiteSpace()can be removed if you are not using Unicode data.Apart from that other functions Equals and Length check functions having some performance issues in large projects. So I prefer ISNullOrEmpty() in many situation. At last its depend upopn the code what it needs. Thanks.

    P 1 Reply Last reply
    0
    • P Pete OHanlon

      string MyString = null;
      bool isEmpty = (MyString == "");

      What do you think the result of this little test is? (Slightly non-intuitive if you expect this to blow up because MyString is null).

      string MyString = " ";
      bool isEmpty = string.IsNullOrEmpty(MyString);

      Okay, is this an empty string? This is a common test to see if a user has entered some details - a space generally isn't considered true for entering details. We can dispense with the last two examples by using the same MyString = null assignment. Because it's null, neither will work so you'd have to issue a null check beforehand anyway. By omission, you can guess which my favourite is.

      K Offline
      K Offline
      Kevin Marois
      wrote on last edited by
      #5

      I'm in the same camp.. I like IsNullOrEmpty because it's really all you need.

      If it's not broken, fix it until it is

      P 1 Reply Last reply
      0
      • K Kevin Marois

        I'm in the same camp.. I like IsNullOrEmpty because it's really all you need.

        If it's not broken, fix it until it is

        P Offline
        P Offline
        Pete OHanlon
        wrote on last edited by
        #6

        Ahem - my camp is strictly in the IsNullOrWhitespace field. I've pitched my tent, put on the gas stove and am boiling up a brew.

        S 1 Reply Last reply
        0
        • P Pete OHanlon

          Ahem - my camp is strictly in the IsNullOrWhitespace field. I've pitched my tent, put on the gas stove and am boiling up a brew.

          S Offline
          S Offline
          Simon_Whale
          wrote on last edited by
          #7

          Pete O'Hanlon wrote:

          I've pitched my tent, put on the gas stove and am boiling up a brew

          Ahem, what about the biscuits?

          Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

          P 1 Reply Last reply
          0
          • S Simon_Whale

            Pete O'Hanlon wrote:

            I've pitched my tent, put on the gas stove and am boiling up a brew

            Ahem, what about the biscuits?

            Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

            P Offline
            P Offline
            Pete OHanlon
            wrote on last edited by
            #8

            I expect my visitors will bring the Rich Tea.

            OriginalGriffO 1 Reply Last reply
            0
            • P Pete OHanlon

              I expect my visitors will bring the Rich Tea.

              OriginalGriffO Offline
              OriginalGriffO Offline
              OriginalGriff
              wrote on last edited by
              #9

              I've got some Chocolate Hobnobs if you've got any coffee?

              Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

              P 1 Reply Last reply
              0
              • OriginalGriffO OriginalGriff

                I've got some Chocolate Hobnobs if you've got any coffee?

                Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

                P Offline
                P Offline
                Pete OHanlon
                wrote on last edited by
                #10

                You're on. You can't beat your chocolate hobnob. Well, not in a crowded campsite field anyway.

                S 1 Reply Last reply
                0
                • P Pete OHanlon

                  You're on. You can't beat your chocolate hobnob. Well, not in a crowded campsite field anyway.

                  S Offline
                  S Offline
                  Simon_Whale
                  wrote on last edited by
                  #11

                  Gentlemen I present, custard creams.

                  Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

                  1 Reply Last reply
                  0
                  • L Lost User

                    Most of them are not even equivalent.. of course you can weigh both apples and oranges, but there aren't many useful conclusions that can be drawn from the results.

                    Coder For Hire wrote:

                    With today's PC's and Servers running at ultra high speed, why would anyone really care?

                    Moving into hypothetical territory here, it's easy to make up a scenario in which it matters. "Do that thing a billion times" is usually a good start. By the way, if you're referring to this blog[^], then disregard the results, that's a very bad benchmark, he makes all the rookie mistakes.

                    S Offline
                    S Offline
                    Sascha Lefevre
                    wrote on last edited by
                    #12

                    harold aptroot wrote:

                    By the way, if you're referring to this blog[^], then disregard the results, that's a very bad benchmark, he makes all the rookie mistakes.

                    I can identify these mistakes: - he uses DateTime.Now instead of StopWatch - he doesn't allow for JIT-precompilation - no GC.Collect() (which shouldn't matter much here but would be good practice) Are there more mistakes?

                    If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                    L 1 Reply Last reply
                    0
                    • K Kevin Marois

                      I was just reading someone's blog where he tested

                      bool isEmpty = (MyString == "");

                      // also

                      bool isEmpty = string.IsNullOrEmpty(MyString);

                      // also

                      bool isEmpty = string.IsNullOrWhiteSpace(MyString);

                      // also

                      bool isEmpty = MyString.Equals("");

                      // also

                      bool isEmpty = MyString.Length == 0;

                      and he listed the number of ticks each example took. That got me thinking.... If you wanted to know of a string was null, that's one thing, and determining if its an empty string is another. But do you REALLY care about TICKS??? With today's PC's and Servers running at ultra high speed, why would anyone really care? Bonus question: I prefer IsNullOrWhiteSpace. What's your favorite & why?

                      If it's not broken, fix it until it is

                      M Offline
                      M Offline
                      molesworth
                      wrote on last edited by
                      #13

                      Just picking up on one specific part of your question :

                      Coder For Hire wrote:

                      But do you REALLY care about TICKS??? With today's PC's and Servers running at ultra high speed, why would anyone really care?

                      Ah, if only... For some usage, maybe not, but there are many application areas where performance is very important. Modern servers may be high performance, but if you're getting Google or Amazon rate hits, then your users might start to notice a slow-down. Gamers are also very critical of poor performance, and will notice if your refresh rate is too slow or, worse, not consistent. Been there, done that, and sometimes you work hard to squeeze out the last ounce of performance from a system. And there are a lot of systems out there running on lower-spec hardware, especially in the embedded world, and every cycle counts in those apps. Currently there and doing that - and again, you can't afford to waste any resources, processor, memory or I/O. Of course, I would very much hope that in any time-critical or mission-critical application, string comparisons were kept to an absolute minimum, but I have occasionally seen some coding horrors and "stringly typed" (to borrow a friend's phrase) parameters...

                      Days spent at sea are not deducted from one's alloted span - Phoenician proverb

                      1 Reply Last reply
                      0
                      • S Sascha Lefevre

                        harold aptroot wrote:

                        By the way, if you're referring to this blog[^], then disregard the results, that's a very bad benchmark, he makes all the rookie mistakes.

                        I can identify these mistakes: - he uses DateTime.Now instead of StopWatch - he doesn't allow for JIT-precompilation - no GC.Collect() (which shouldn't matter much here but would be good practice) Are there more mistakes?

                        If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #14

                        A couple more, - the result goes nowhere. Apparently it worked, but it's dangerous (operation could be discarded, and really they should have been, so I have a sneaking suspicion it might have been run while suppressing JIT-optimization). - the whole thing is only done once. The worst part of that is the JIT-compilation, but there is also "turbo lag" (part of the first loop could run at a lower frequency), other start-up nonsense (extra cache misses and so on), and a semi-random number of context switches. - from these benchmarks, it's impossible to tell how much of the time taken is due to the loop overhead. - it's measuring a throughput but kind of implying it's a latency.

                        S 1 Reply Last reply
                        0
                        • G Gyana_Ranjan Dash

                          All are different functions but doing almost same work.So my choice better to use IsNullOrEmpty() as its safe and performance is good as compare to IsNullOrWhiteSpace().As IsNullOrWhiteSpace()can be removed if you are not using Unicode data.Apart from that other functions Equals and Length check functions having some performance issues in large projects. So I prefer ISNullOrEmpty() in many situation. At last its depend upopn the code what it needs. Thanks.

                          P Offline
                          P Offline
                          Pete OHanlon
                          wrote on last edited by
                          #15

                          You do know that IsNullOrEmpty IS NOT the same as IsNullOrWhitespace don't you? If I were to paste a tab into a field, for instance, and I'm expecting it to contain a proper value, IsNullOrEmpty will let that past whereas IsNullOrWhitespace will properly identify that there's a whitespace character in there.

                          1 Reply Last reply
                          0
                          • L Lost User

                            A couple more, - the result goes nowhere. Apparently it worked, but it's dangerous (operation could be discarded, and really they should have been, so I have a sneaking suspicion it might have been run while suppressing JIT-optimization). - the whole thing is only done once. The worst part of that is the JIT-compilation, but there is also "turbo lag" (part of the first loop could run at a lower frequency), other start-up nonsense (extra cache misses and so on), and a semi-random number of context switches. - from these benchmarks, it's impossible to tell how much of the time taken is due to the loop overhead. - it's measuring a throughput but kind of implying it's a latency.

                            S Offline
                            S Offline
                            Sascha Lefevre
                            wrote on last edited by
                            #16

                            Thank you, Harold! I got the first points but I don't see how he's implying that it's a latency - can you elaborate on that?

                            If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                            L 1 Reply Last reply
                            0
                            • S Sascha Lefevre

                              Thank you, Harold! I got the first points but I don't see how he's implying that it's a latency - can you elaborate on that?

                              If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                              L Offline
                              L Offline
                              Lost User
                              wrote on last edited by
                              #17

                              Well, he doesn't really come right out and say it, but the way he puts things makes it look like it's about latency. Things like "worth the extra ticks" or "takes x ticks", none of it is actually wrong but I just get that vague sense that he doesn't really make the distinctions between how long something takes and how often you can do it in a unit of time.

                              S 1 Reply Last reply
                              0
                              • L Lost User

                                Well, he doesn't really come right out and say it, but the way he puts things makes it look like it's about latency. Things like "worth the extra ticks" or "takes x ticks", none of it is actually wrong but I just get that vague sense that he doesn't really make the distinctions between how long something takes and how often you can do it in a unit of time.

                                S Offline
                                S Offline
                                Sascha Lefevre
                                wrote on last edited by
                                #18

                                Ah, alright. I thought I should be able to see that in the code :) Thank you, Harold.

                                If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                                1 Reply Last reply
                                0
                                Reply
                                • Reply as topic
                                Log in to reply
                                • Oldest to Newest
                                • Newest to Oldest
                                • Most Votes


                                • Login

                                • Don't have an account? Register

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • World
                                • Users
                                • Groups