Below is a performance analysis of C# .NET integer division comparing;
- try...catch (DivideByZeroException)
- casting numerator (the number on top) to double
- if denominator (the number on bottom) not equal to zero
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(); } } } |
Update July 2020 with .NET Fiddle live code
No comments:
Post a Comment