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. Which one is faster - Static function calls or If else?

Which one is faster - Static function calls or If else?

Scheduled Pinned Locked Moved C#
graphicsquestion
12 Posts 5 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.
  • A Offline
    A Offline
    abcxyz82
    wrote on last edited by
    #1

    I am writing console batch application which does intense processsing on bitmap. I would like to know the preffered way of dealing with Min and Max values, its good if I can save a microsecond as batch application runs for a week. minValue = Math.Min ( val1, val2 ) minValue = val1 < val2 ? val1 : val2; Also is it possible to know which one is faster by examining metadata? REgards. MaulikCE

    L A T 3 Replies Last reply
    0
    • A abcxyz82

      I am writing console batch application which does intense processsing on bitmap. I would like to know the preffered way of dealing with Min and Max values, its good if I can save a microsecond as batch application runs for a week. minValue = Math.Min ( val1, val2 ) minValue = val1 < val2 ? val1 : val2; Also is it possible to know which one is faster by examining metadata? REgards. MaulikCE

      L Offline
      L Offline
      leppie
      wrote on last edited by
      #2

      Dealing with integers, I would say the second (conditional expression). xacc-ide 0.0.15 now with C#, MSIL, C, XML, ASP.NET, Nemerle, MyXaml and HLSL coloring - Screenshots

      A 1 Reply Last reply
      0
      • L leppie

        Dealing with integers, I would say the second (conditional expression). xacc-ide 0.0.15 now with C#, MSIL, C, XML, ASP.NET, Nemerle, MyXaml and HLSL coloring - Screenshots

        A Offline
        A Offline
        abcxyz82
        wrote on last edited by
        #3

        What about others, "double" and "float"? One more, is there any performance difference between IF ELSE and CONDITIONAL EXPRESSION?

        L 1 Reply Last reply
        0
        • A abcxyz82

          What about others, "double" and "float"? One more, is there any performance difference between IF ELSE and CONDITIONAL EXPRESSION?

          L Offline
          L Offline
          leppie
          wrote on last edited by
          #4

          for FP numbers I would prefer Math function. abcxyz82 wrote: One more, is there any performance difference between IF ELSE and CONDITIONAL EXPRESSION? Probably not, look at the generated IL. In the end, this will NOT be your bottleneck. Look to optimize somewhere where it really matters. Have you tried a profiler? xacc-ide 0.0.15 now with C#, MSIL, C, XML, ASP.NET, Nemerle, MyXaml and HLSL coloring - Screenshots

          1 Reply Last reply
          0
          • A abcxyz82

            I am writing console batch application which does intense processsing on bitmap. I would like to know the preffered way of dealing with Min and Max values, its good if I can save a microsecond as batch application runs for a week. minValue = Math.Min ( val1, val2 ) minValue = val1 < val2 ? val1 : val2; Also is it possible to know which one is faster by examining metadata? REgards. MaulikCE

            A Offline
            A Offline
            Ashok Dhamija
            wrote on last edited by
            #5

            Here is the authentic word, the second way (of using If-else) is almost 100% faster than the first method (of using Static method of Math). Here is how I arrived at the result. Had a simple project with two buttons and two labels, with the following event-handlers for their click events:

            private void button1_Click(object sender, System.EventArgs e)
            {
            int minValue;
            int val1 = 5;
            int val2 = 7;
            DateTime time1 = DateTime.Now;

            		for(long i=0; i<1000000000; i++)
            		{
            			minValue = Math.Min ( val1, val2 );
            		}
            		DateTime time2 = DateTime.Now;
            		TimeSpan diff1 = time2 - time1;
            
            		label1.Text = diff1.Seconds.ToString();
            
            		
            	}
            
            	private void button2\_Click(object sender, System.EventArgs e)
            	{
            		int minValue;
            		int val1 = 5; 
            		int val2 = 7;
            		DateTime time1 = DateTime.Now;
            
            		for(long i=0; i<1000000000; i++)
            		{
            			minValue = val1 < val2 ? val1 : val2;
            		}
            		DateTime time2 = DateTime.Now;
            		TimeSpan diff1 = time2 - time1;
            
            		label2.Text = diff1.Seconds.ToString();
            	}
            

            This means that both the methods are compared by using the for loop for 10 billion iterations of the respective calculations. And the results are: the first method took 12 seconds whereas the second method took just 7 seconds. So, you can safely use the second method.

            D L 2 Replies Last reply
            0
            • A Ashok Dhamija

              Here is the authentic word, the second way (of using If-else) is almost 100% faster than the first method (of using Static method of Math). Here is how I arrived at the result. Had a simple project with two buttons and two labels, with the following event-handlers for their click events:

              private void button1_Click(object sender, System.EventArgs e)
              {
              int minValue;
              int val1 = 5;
              int val2 = 7;
              DateTime time1 = DateTime.Now;

              		for(long i=0; i<1000000000; i++)
              		{
              			minValue = Math.Min ( val1, val2 );
              		}
              		DateTime time2 = DateTime.Now;
              		TimeSpan diff1 = time2 - time1;
              
              		label1.Text = diff1.Seconds.ToString();
              
              		
              	}
              
              	private void button2\_Click(object sender, System.EventArgs e)
              	{
              		int minValue;
              		int val1 = 5; 
              		int val2 = 7;
              		DateTime time1 = DateTime.Now;
              
              		for(long i=0; i<1000000000; i++)
              		{
              			minValue = val1 < val2 ? val1 : val2;
              		}
              		DateTime time2 = DateTime.Now;
              		TimeSpan diff1 = time2 - time1;
              
              		label2.Text = diff1.Seconds.ToString();
              	}
              

              This means that both the methods are compared by using the for loop for 10 billion iterations of the respective calculations. And the results are: the first method took 12 seconds whereas the second method took just 7 seconds. So, you can safely use the second method.

              D Offline
              D Offline
              Dave Kreskowiak
              wrote on last edited by
              #6

              Just curious, but what are the results if you randomly generated numbers instead of using the same two constant numbers over and over again? RageInTheMachine9532 "...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome

              A 1 Reply Last reply
              0
              • A abcxyz82

                I am writing console batch application which does intense processsing on bitmap. I would like to know the preffered way of dealing with Min and Max values, its good if I can save a microsecond as batch application runs for a week. minValue = Math.Min ( val1, val2 ) minValue = val1 < val2 ? val1 : val2; Also is it possible to know which one is faster by examining metadata? REgards. MaulikCE

                T Offline
                T Offline
                Tom Larsen
                wrote on last edited by
                #7

                Without further investigation the second one would seem faster. If you really want to know for sure construct a simple test example that just reads each pixel on a bitmap and runs one or the other comparison and time the event. However I would caution you about attempting optimization like this because premature optimization is evil. :-) Without profiling tools trying to optmize can lead to confusing code and worse even worse performance (ie. producing bogus output, crashing, etc). The best optimization might happen outside of this code and quite possibly be in another part of the loop. Or ultimately, this is a "hardware bound" problem where no matter how much tweaking you do to code you are better off taking the amount of money they would have paid you to tweak code and buying new hardware with it.

                1 Reply Last reply
                0
                • A Ashok Dhamija

                  Here is the authentic word, the second way (of using If-else) is almost 100% faster than the first method (of using Static method of Math). Here is how I arrived at the result. Had a simple project with two buttons and two labels, with the following event-handlers for their click events:

                  private void button1_Click(object sender, System.EventArgs e)
                  {
                  int minValue;
                  int val1 = 5;
                  int val2 = 7;
                  DateTime time1 = DateTime.Now;

                  		for(long i=0; i<1000000000; i++)
                  		{
                  			minValue = Math.Min ( val1, val2 );
                  		}
                  		DateTime time2 = DateTime.Now;
                  		TimeSpan diff1 = time2 - time1;
                  
                  		label1.Text = diff1.Seconds.ToString();
                  
                  		
                  	}
                  
                  	private void button2\_Click(object sender, System.EventArgs e)
                  	{
                  		int minValue;
                  		int val1 = 5; 
                  		int val2 = 7;
                  		DateTime time1 = DateTime.Now;
                  
                  		for(long i=0; i<1000000000; i++)
                  		{
                  			minValue = val1 < val2 ? val1 : val2;
                  		}
                  		DateTime time2 = DateTime.Now;
                  		TimeSpan diff1 = time2 - time1;
                  
                  		label2.Text = diff1.Seconds.ToString();
                  	}
                  

                  This means that both the methods are compared by using the for loop for 10 billion iterations of the respective calculations. And the results are: the first method took 12 seconds whereas the second method took just 7 seconds. So, you can safely use the second method.

                  L Offline
                  L Offline
                  leppie
                  wrote on last edited by
                  #8

                  And using floating point numbers? I'm sure Math.Min() will be faster. xacc-ide 0.0.15 now with C#, MSIL, C, XML, ASP.NET, Nemerle, MyXaml and HLSL coloring - Screenshots

                  A 1 Reply Last reply
                  0
                  • L leppie

                    And using floating point numbers? I'm sure Math.Min() will be faster. xacc-ide 0.0.15 now with C#, MSIL, C, XML, ASP.NET, Nemerle, MyXaml and HLSL coloring - Screenshots

                    A Offline
                    A Offline
                    Ashok Dhamija
                    wrote on last edited by
                    #9

                    In fact, I tried the aforesaid code with the floating point numbers also, by replacing the first lines of the code (above) with the following sample code:

                    float minValue;
                    float val1 = 5.3214F;
                    float val2 = 7.7564F;

                    The result is still the same. The second method (i.e., the if-else method) is almost 100% faster than the first method (i.e., the Static Math method). The practical results on my machine were 17 seconds and 8 seconds respectively for 10 billion iterations for the said float numbers for the aforesaid two methods. Regards

                    1 Reply Last reply
                    0
                    • D Dave Kreskowiak

                      Just curious, but what are the results if you randomly generated numbers instead of using the same two constant numbers over and over again? RageInTheMachine9532 "...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome

                      A Offline
                      A Offline
                      Ashok Dhamija
                      wrote on last edited by
                      #10

                      Yes, I compared the performance of the said two methods by using random numbers. Here is the code which I used (this time I used only 1 million iterations instead of 10 billion iterations because of time-consuming random number generation process):

                      private void button1_Click(object sender, System.EventArgs e)
                      {
                      DateTime time1 = DateTime.Now;
                      for(long i=0; i<1000000; i++)
                      {
                      int val1 = Random1To99();
                      int val2 = Random1To99();
                      int minValue = Math.Min ( val1, val2 );
                      }
                      DateTime time2 = DateTime.Now;
                      TimeSpan diff1 = time2 - time1;
                      label1.Text = diff1.Seconds.ToString();
                      }

                      	private void button2\_Click(object sender, System.EventArgs e)
                      	{			
                      		DateTime time1 = DateTime.Now;
                      		for(long i=0; i<1000000; i++)
                      		{				
                      			int val1 = Random1To99(); 
                      			int val2 = Random1To99();
                      			int minValue = val1 < val2 ? val1 : val2;
                      		}
                      		DateTime time2 = DateTime.Now;
                      		TimeSpan diff1 = time2 - time1;
                      		label2.Text = diff1.Seconds.ToString();
                      	}
                      

                      And, the method to generate the random numbers is as under (for the sake of simplicity, this method generates random numbers in the range of 1 to 99 only; secondly, I declared mySeed variable at the class level to try to get the "real" random numbers by using a real different seed every time):

                      private int mySeed = 0;
                      private int Random1To99()
                      {
                      DateTime dt = DateTime.Now;
                      mySeed += (int)(dt.Millisecond);
                      Random rnd = new Random(mySeed);
                      //return a number in the range of 1 to 99
                      return (int) rnd.Next(1, 100);
                      }

                      This time, both the methods are taking the same time of 37 seconds on my machine. The result is the same even though I tried it a few times. The reason appears to be that the generation of one random number takes perhaps 1000 to 10000 times more time than either of the methods being compared! And, then use this for 1 million times!! In the end, what one finds is that out of 37 seconds taken for the aforesaid operation, perhaps 99.999% of the processing time is taken only for the random number generations and the remaining appx. 0.0001% time is being compared for the said two methods. So, expectedly, we get the same time of about 37 seconds for the above two methods. To conclude, what I personally feel is that once it is accepted that the second method of if-else takes less time for any given combination of two numbers as compared to the first method of Math static function, then this result would broadly be the same even for any othe

                      D 2 Replies Last reply
                      0
                      • A Ashok Dhamija

                        Yes, I compared the performance of the said two methods by using random numbers. Here is the code which I used (this time I used only 1 million iterations instead of 10 billion iterations because of time-consuming random number generation process):

                        private void button1_Click(object sender, System.EventArgs e)
                        {
                        DateTime time1 = DateTime.Now;
                        for(long i=0; i<1000000; i++)
                        {
                        int val1 = Random1To99();
                        int val2 = Random1To99();
                        int minValue = Math.Min ( val1, val2 );
                        }
                        DateTime time2 = DateTime.Now;
                        TimeSpan diff1 = time2 - time1;
                        label1.Text = diff1.Seconds.ToString();
                        }

                        	private void button2\_Click(object sender, System.EventArgs e)
                        	{			
                        		DateTime time1 = DateTime.Now;
                        		for(long i=0; i<1000000; i++)
                        		{				
                        			int val1 = Random1To99(); 
                        			int val2 = Random1To99();
                        			int minValue = val1 < val2 ? val1 : val2;
                        		}
                        		DateTime time2 = DateTime.Now;
                        		TimeSpan diff1 = time2 - time1;
                        		label2.Text = diff1.Seconds.ToString();
                        	}
                        

                        And, the method to generate the random numbers is as under (for the sake of simplicity, this method generates random numbers in the range of 1 to 99 only; secondly, I declared mySeed variable at the class level to try to get the "real" random numbers by using a real different seed every time):

                        private int mySeed = 0;
                        private int Random1To99()
                        {
                        DateTime dt = DateTime.Now;
                        mySeed += (int)(dt.Millisecond);
                        Random rnd = new Random(mySeed);
                        //return a number in the range of 1 to 99
                        return (int) rnd.Next(1, 100);
                        }

                        This time, both the methods are taking the same time of 37 seconds on my machine. The result is the same even though I tried it a few times. The reason appears to be that the generation of one random number takes perhaps 1000 to 10000 times more time than either of the methods being compared! And, then use this for 1 million times!! In the end, what one finds is that out of 37 seconds taken for the aforesaid operation, perhaps 99.999% of the processing time is taken only for the random number generations and the remaining appx. 0.0001% time is being compared for the said two methods. So, expectedly, we get the same time of about 37 seconds for the above two methods. To conclude, what I personally feel is that once it is accepted that the second method of if-else takes less time for any given combination of two numbers as compared to the first method of Math static function, then this result would broadly be the same even for any othe

                        D Offline
                        D Offline
                        Dave Kreskowiak
                        wrote on last edited by
                        #11

                        That's what I though would happen. What I think the comiler did to your original code, was that since your using contant numbers, the "?:" statement was optimized into the only result possible for that statement and was replaced by a simple numerical assignment. RageInTheMachine9532 "...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome

                        1 Reply Last reply
                        0
                        • A Ashok Dhamija

                          Yes, I compared the performance of the said two methods by using random numbers. Here is the code which I used (this time I used only 1 million iterations instead of 10 billion iterations because of time-consuming random number generation process):

                          private void button1_Click(object sender, System.EventArgs e)
                          {
                          DateTime time1 = DateTime.Now;
                          for(long i=0; i<1000000; i++)
                          {
                          int val1 = Random1To99();
                          int val2 = Random1To99();
                          int minValue = Math.Min ( val1, val2 );
                          }
                          DateTime time2 = DateTime.Now;
                          TimeSpan diff1 = time2 - time1;
                          label1.Text = diff1.Seconds.ToString();
                          }

                          	private void button2\_Click(object sender, System.EventArgs e)
                          	{			
                          		DateTime time1 = DateTime.Now;
                          		for(long i=0; i<1000000; i++)
                          		{				
                          			int val1 = Random1To99(); 
                          			int val2 = Random1To99();
                          			int minValue = val1 < val2 ? val1 : val2;
                          		}
                          		DateTime time2 = DateTime.Now;
                          		TimeSpan diff1 = time2 - time1;
                          		label2.Text = diff1.Seconds.ToString();
                          	}
                          

                          And, the method to generate the random numbers is as under (for the sake of simplicity, this method generates random numbers in the range of 1 to 99 only; secondly, I declared mySeed variable at the class level to try to get the "real" random numbers by using a real different seed every time):

                          private int mySeed = 0;
                          private int Random1To99()
                          {
                          DateTime dt = DateTime.Now;
                          mySeed += (int)(dt.Millisecond);
                          Random rnd = new Random(mySeed);
                          //return a number in the range of 1 to 99
                          return (int) rnd.Next(1, 100);
                          }

                          This time, both the methods are taking the same time of 37 seconds on my machine. The result is the same even though I tried it a few times. The reason appears to be that the generation of one random number takes perhaps 1000 to 10000 times more time than either of the methods being compared! And, then use this for 1 million times!! In the end, what one finds is that out of 37 seconds taken for the aforesaid operation, perhaps 99.999% of the processing time is taken only for the random number generations and the remaining appx. 0.0001% time is being compared for the said two methods. So, expectedly, we get the same time of about 37 seconds for the above two methods. To conclude, what I personally feel is that once it is accepted that the second method of if-else takes less time for any given combination of two numbers as compared to the first method of Math static function, then this result would broadly be the same even for any othe

                          D Offline
                          D Offline
                          Dave Kreskowiak
                          wrote on last edited by
                          #12

                          Your code was slowed down because you kept killing and recreating a new RNG with every number you generated and used limits on the range of numbers returned. You also have the extra overhead of making a method call to create a new RNG, seed it, and return a number. This wasn't necessary since we weren't testing the performance of the RNG functions. If you want wanted to compare the two methods on the exact same stream of numbers (and do it quickly!), then you have to create an RNG with a known seed value and retain it throughout the entire test and minimize the number of calculations that it has to do to return a number. I ran similar code to yours, running 1 Billion iterations in just under one minute:

                          int Num1, Num2, Num3;
                          Stopwatch timer = new Stopwatch();
                          Random RNG = new Random(3456); // Known seed value
                          Console.WriteLine(DateTime.Now.ToString());
                           
                          timer.Start();
                          for (int IterationsRemaining = 1000000000; IterationsRemaining >= 0; IterationsRemaining--)
                          {
                          Num1 = RNG.Next(); // Who cares what the limits are. Just return
                          Num2 = RNG.Next(); // the next 32-bit integer in the list of random numbers.
                          Num3 = (Num1 > Num2) ? Num2 : Num1;
                          }
                          timer.Stop();
                           
                          Console.WriteLine(DateTime.Now.ToString());
                          Console.WriteLine(timer.Elapsed.ToString());

                          Using the known seed value, rerunning this code with the only change being the Num3= line, the RNG will generate the exact same string of numbers. The results I got on a Dell GX270, C# 2005, running 3 passes of 1 Billion iterations each:

                          Release compiled code: (int types)
                          Math.Min: 46.11 47.02 45.92 seconds (Avg: 46.35 seconds)
                          ?: operator: 39.78 40.04 39.37 seconds (Avg: 39.73 seconds)

                          Here's something interesting:

                          Release compiled code: (double types)
                          Math.Min: 114.10 113.66 111.77 seconds (Avg: 113.17 seconds)
                          ?: operator: 56.91 56.95 56.97 seconds (Avg: 56.94 seconds)

                          RageInTheMachine9532 "...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome

                          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