Wednesday, November 15, 2017

C# Integer division try...catch vs casting vs if divisor not zero speed test, which is quicker?

Below is a performance analysis of C# .NET integer division comparing; 
  1. try...catch (DivideByZeroException)
  2. casting numerator (the number on top) to double
  3. if denominator (the number on bottom) not equal to zero
The console application code loops 1 million times and run using .NET 4.0 Framework (works on XP+) and timings (ticks) are indicated in the comments. The 2nd number in using .NET 4.6 Framework (Vista+). There is no significant improvement switching frameworks.

Answer: 

Casting (double)ttlcnt beats try...catch by 1 order O(1) of magnitude. 

But the winner is the if divisor not zero statement  beating casting by 6,000 nanoseconds.

FYI: Ticks are 100 nanoseconds long. There are 10,000,000 (10M) per second.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace CastVSCatch
{
    class Program
    {
        static void Main(string[] args)
        {
           
            int million = 1000000; 
            int ttlcnt = 228394393;
            int pct = 0;
            var sw = Stopwatch.StartNew();

            for (int i = 0; i < million; i++)
            {

                //pct = (int)(100 * ((double)ttlcnt / i));  //~16,800 ticks //17,020 ticks in NETt4.6

                //try
                //{
                //    pct = 100 * (ttlcnt / i); //~=151,359  ticks   //147,531  in NET4.6
                //}
                //catch (DivideByZeroException)
                //{
                //    pct = 0;
                //}

                if (i != 0)
                    pct = 100 * (ttlcnt / i); //~=10,816 ticks 
                else
                    pct = 0;

                //if (i == 0)
                //    pct = 0;
                //else
                //    pct = 100 * (ttlcnt / i); //~=11,162 ticks 

            }

            sw.Stop(); 

            Console.WriteLine("pct=" + pct.ToString()+" in ticks="+sw.ElapsedTicks);

            if (Debugger.IsAttached)
                Console.ReadKey(); 
        }
    }
}
>

No comments:

Post a Comment