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. The Lounge
  3. C# puzzle....

C# puzzle....

Scheduled Pinned Locked Moved The Lounge
csharpperformancequestion
20 Posts 11 Posters 20 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.
  • N Nish Nishant

    I did cheat, and run a quick console app. But D seems fastest, very closely followed by B. Barely really. Then A, and behind A is E. Slowest is C.

    Nish Nishant Consultant Software Architect Ganymede Software Solutions LLC www.ganymedesoftwaresolutions.com

    J Offline
    J Offline
    James Curran
    wrote on last edited by
    #5

    Hmmmm Very interesting results. I ran my test using BenchmarkDotNet, with a longer string, with a "~" near the end. Now, the whole point of this was that I found some code using A, and I figured that B should be faster. So, I ran the test-- and in mine, B came out way last. Studying it source code, I found that A just redirects to E, so they were nearly the same. B, however, uses String's IEnumerable interface to run the Enumerable.Contains() extension method, which is why it was last. C I tried, mistakenly thinking it would be the same as E. It came out nearly tied with B for last. D was my overall winner as well. So, it seems you are experiencing a String.Contains(char) which is specific for strings, which I am not seeing. I ran the tests on .NET 4.6.1. Are you using .NET Core?

    Truth, James

    N 1 Reply Last reply
    0
    • J James Curran

      Hmmmm Very interesting results. I ran my test using BenchmarkDotNet, with a longer string, with a "~" near the end. Now, the whole point of this was that I found some code using A, and I figured that B should be faster. So, I ran the test-- and in mine, B came out way last. Studying it source code, I found that A just redirects to E, so they were nearly the same. B, however, uses String's IEnumerable interface to run the Enumerable.Contains() extension method, which is why it was last. C I tried, mistakenly thinking it would be the same as E. It came out nearly tied with B for last. D was my overall winner as well. So, it seems you are experiencing a String.Contains(char) which is specific for strings, which I am not seeing. I ran the tests on .NET 4.6.1. Are you using .NET Core?

      Truth, James

      N Offline
      N Offline
      Nish Nishant
      wrote on last edited by
      #6

      Yep, I used .NET Core which may explain the difference.

      Nish Nishant Consultant Software Architect Ganymede Software Solutions LLC www.ganymedesoftwaresolutions.com

      1 Reply Last reply
      0
      • J James Curran

        (I was torn between putting these here or in the C# forum, but it not really a serious question...) Given a simple string

        		const string \_str = "abcdefghijklmnopqrstuvwxyz";
        

        put the following equivalent code blocks in order of their speed:

        	if ( \_str.Contains("~")) {....}				// A
        	if ( \_str.Contains('~')) {....}				// B
        	if ( \_str.IndexOf("~") >= 0)   {....}		// C
        	if ( \_str.IndexOf('~') >= 0)   {....}		// D
        	if ( \_str.IndexOf("~", StringComparison.Ordinal) >= 0)  {....}    //E
        

        Hint: there are three tiers --- One is the clear winning. Two others are about the same, significantly behind, and the last two are about the same, *way* behind the others.

        Truth, James

        M Offline
        M Offline
        Member_14774770
        wrote on last edited by
        #7

        Wrong Forum! Here are few right places to ask the QN or to discuss it. 1.C# Discussion Boards[^] 2.The Weird and The Wonderful[^]

        J OriginalGriffO 2 Replies Last reply
        0
        • N Nish Nishant

          I did cheat, and run a quick console app. But D seems fastest, very closely followed by B. Barely really. Then A, and behind A is E. Slowest is C.

          Nish Nishant Consultant Software Architect Ganymede Software Solutions LLC www.ganymedesoftwaresolutions.com

          G Offline
          G Offline
          Garth J Lancaster
          wrote on last edited by
          #8

          Upvoted for 'cheating' being scientific - there's nothing wrong with empirical proof, its exactely what I thought when I saw the question, ie, 'why guess' ..

          N 1 Reply Last reply
          0
          • J James Curran

            (I was torn between putting these here or in the C# forum, but it not really a serious question...) Given a simple string

            		const string \_str = "abcdefghijklmnopqrstuvwxyz";
            

            put the following equivalent code blocks in order of their speed:

            	if ( \_str.Contains("~")) {....}				// A
            	if ( \_str.Contains('~')) {....}				// B
            	if ( \_str.IndexOf("~") >= 0)   {....}		// C
            	if ( \_str.IndexOf('~') >= 0)   {....}		// D
            	if ( \_str.IndexOf("~", StringComparison.Ordinal) >= 0)  {....}    //E
            

            Hint: there are three tiers --- One is the clear winning. Two others are about the same, significantly behind, and the last two are about the same, *way* behind the others.

            Truth, James

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

            Something similar I tried some years ago: Counting Lines in a String[^] It shows another couple of methods you could have tried.

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony AntiTwitter: @DalekDave is now a follower!

            "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

            1 Reply Last reply
            0
            • N Nish Nishant

              This is the code I ran in release mode. (.NET Core)

              class Program
              {
              const string _str = "abcdefghijklmnopqrstuvwxyz";

              static void Main(string\[\] args)
              {
                  Foo("A", () => \_str.Contains("~"));
                  Foo ("B", () => \_str.Contains('~'));
                  Foo("C", () => \_str.IndexOf("~") >= 0);
                  Foo("D", () => \_str.IndexOf('~') >= 0);
                  Foo("E", () => \_str.IndexOf("~", StringComparison.Ordinal) >= 0);
              }
              
              static void Foo(string s, Func<bool> action)
              {
                  var sw = new Stopwatch();
                  sw.Start();
                  for (int i = 0; i < 1000000; i++)
                  {
                      action();
                  }
                  sw.Stop();
                  Console.WriteLine($"{s} - {sw.Elapsed.Milliseconds}");
              }
              

              }

              Nish Nishant Consultant Software Architect Ganymede Software Solutions LLC www.ganymedesoftwaresolutions.com

              M Offline
              M Offline
              Mario Vernari
              wrote on last edited by
              #10

              In my experience, the speed measurements at the start of an app are always polluted by the runtime initialization. That is, it might look that "A" takes longer than "B", where actually does not. Typically, I copy the same piece of code two or three times, then I take the last results. Have a try, maybe the results will change, maybe not.

              N J 2 Replies Last reply
              0
              • M Member_14774770

                Wrong Forum! Here are few right places to ask the QN or to discuss it. 1.C# Discussion Boards[^] 2.The Weird and The Wonderful[^]

                J Offline
                J Offline
                Jorgen Andersson
                wrote on last edited by
                #11

                No, it's ok. Read the sticky on top: The Lounge[^] Point2: Technical discussions are welcome...

                Wrong is evil and must be defeated. - Jeff Ello

                1 Reply Last reply
                0
                • Greg UtasG Greg Utas

                  I'm just an old C++ dinosaur, so my guess is that B and D are the fastest, followed by A and C, and finally the indecipherable twaddle of E--unless it's some kind of secret code for "Hint: you're looking for a single character and therefore don't have to construct "~", in which case it's probably faster than A and C but slower than B and D.

                  Robust Services Core | Software Techniques for Lemmings | Articles

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

                  Greg Utas wrote:

                  finally the indecipherable twaddle of E--unless it's some kind of secret code for "Hint: you're looking for a single character and therefore don't have to construct "~"

                  Nope: it's saying "Look for this using a binary comparison, rather than using a culture or shift specific sort order" - basically "compare strings as byte arrays" but using 16 bit values. In theory, this should be much quicker than a non-ordinal comparison as you don't have to deal with "special cases" or "'t' == 'T'", and most processors have machine code instructions for byte based searching and comparing.

                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony AntiTwitter: @DalekDave is now a follower!

                  "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

                  Greg UtasG 1 Reply Last reply
                  0
                  • M Member_14774770

                    Wrong Forum! Here are few right places to ask the QN or to discuss it. 1.C# Discussion Boards[^] 2.The Weird and The Wonderful[^]

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

                    Jorgen is right - this isn't a question seeking help, it's a "Hey! look at this!" discussion.

                    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony AntiTwitter: @DalekDave is now a follower!

                    "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

                    N 1 Reply Last reply
                    0
                    • J James Curran

                      (I was torn between putting these here or in the C# forum, but it not really a serious question...) Given a simple string

                      		const string \_str = "abcdefghijklmnopqrstuvwxyz";
                      

                      put the following equivalent code blocks in order of their speed:

                      	if ( \_str.Contains("~")) {....}				// A
                      	if ( \_str.Contains('~')) {....}				// B
                      	if ( \_str.IndexOf("~") >= 0)   {....}		// C
                      	if ( \_str.IndexOf('~') >= 0)   {....}		// D
                      	if ( \_str.IndexOf("~", StringComparison.Ordinal) >= 0)  {....}    //E
                      

                      Hint: there are three tiers --- One is the clear winning. Two others are about the same, significantly behind, and the last two are about the same, *way* behind the others.

                      Truth, James

                      C Offline
                      C Offline
                      CPallini
                      wrote on last edited by
                      #14

                      After close examination, the fastest option is 'skip that block'. :rolleyes:

                      1 Reply Last reply
                      0
                      • M Mario Vernari

                        In my experience, the speed measurements at the start of an app are always polluted by the runtime initialization. That is, it might look that "A" takes longer than "B", where actually does not. Typically, I copy the same piece of code two or three times, then I take the last results. Have a try, maybe the results will change, maybe not.

                        N Offline
                        N Offline
                        Nelek
                        wrote on last edited by
                        #15

                        Mario Vernari wrote:

                        Typically, I copy the same piece of code two or three times, then I take the last results.

                        I use sleep 5 seconds, then go for it.

                        M.D.V. ;) If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about? Help me to understand what I'm saying, and I'll explain it better to you Rating helpful answers is nice, but saying thanks can be even nicer.

                        1 Reply Last reply
                        0
                        • OriginalGriffO OriginalGriff

                          Greg Utas wrote:

                          finally the indecipherable twaddle of E--unless it's some kind of secret code for "Hint: you're looking for a single character and therefore don't have to construct "~"

                          Nope: it's saying "Look for this using a binary comparison, rather than using a culture or shift specific sort order" - basically "compare strings as byte arrays" but using 16 bit values. In theory, this should be much quicker than a non-ordinal comparison as you don't have to deal with "special cases" or "'t' == 'T'", and most processors have machine code instructions for byte based searching and comparing.

                          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony AntiTwitter: @DalekDave is now a follower!

                          Greg UtasG Offline
                          Greg UtasG Offline
                          Greg Utas
                          wrote on last edited by
                          #16

                          Next time I can't decipher some twaddle, I'll know who to turn to. :laugh:

                          Robust Services Core | Software Techniques for Lemmings | Articles

                          <p><a href="https://github.com/GregUtas/robust-services-core/blob/master/README.md">Robust Services Core</a>
                          <em>The fox knows many things, but the hedgehog knows one big thing.</em></p>

                          1 Reply Last reply
                          0
                          • J James Curran

                            (I was torn between putting these here or in the C# forum, but it not really a serious question...) Given a simple string

                            		const string \_str = "abcdefghijklmnopqrstuvwxyz";
                            

                            put the following equivalent code blocks in order of their speed:

                            	if ( \_str.Contains("~")) {....}				// A
                            	if ( \_str.Contains('~')) {....}				// B
                            	if ( \_str.IndexOf("~") >= 0)   {....}		// C
                            	if ( \_str.IndexOf('~') >= 0)   {....}		// D
                            	if ( \_str.IndexOf("~", StringComparison.Ordinal) >= 0)  {....}    //E
                            

                            Hint: there are three tiers --- One is the clear winning. Two others are about the same, significantly behind, and the last two are about the same, *way* behind the others.

                            Truth, James

                            F Offline
                            F Offline
                            F ES Sitecore
                            wrote on last edited by
                            #17

                            It might well depend on the string being searched and what is being searched.

                            1 Reply Last reply
                            0
                            • M Mario Vernari

                              In my experience, the speed measurements at the start of an app are always polluted by the runtime initialization. That is, it might look that "A" takes longer than "B", where actually does not. Typically, I copy the same piece of code two or three times, then I take the last results. Have a try, maybe the results will change, maybe not.

                              J Offline
                              J Offline
                              Jorgen Andersson
                              wrote on last edited by
                              #18

                              Mario Vernari wrote:

                              In my experience, the speed measurements at the start of an app are always polluted by the runtime initialization.

                              Not just that, but also caching, task switching etc. There is a really good article here on how to get consistent test results: Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch[^]

                              Wrong is evil and must be defeated. - Jeff Ello

                              1 Reply Last reply
                              0
                              • G Garth J Lancaster

                                Upvoted for 'cheating' being scientific - there's nothing wrong with empirical proof, its exactely what I thought when I saw the question, ie, 'why guess' ..

                                N Offline
                                N Offline
                                Nish Nishant
                                wrote on last edited by
                                #19

                                Thanks, good way of looking at it I suppose.

                                Nish Nishant Consultant Software Architect Ganymede Software Solutions LLC www.ganymedesoftwaresolutions.com

                                1 Reply Last reply
                                0
                                • OriginalGriffO OriginalGriff

                                  Jorgen is right - this isn't a question seeking help, it's a "Hey! look at this!" discussion.

                                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony AntiTwitter: @DalekDave is now a follower!

                                  N Offline
                                  N Offline
                                  Nish Nishant
                                  wrote on last edited by
                                  #20

                                  Also one of the more interesting posts here in recent times.

                                  Nish Nishant Consultant Software Architect Ganymede Software Solutions LLC www.ganymedesoftwaresolutions.com

                                  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