I know this is an old question, but just add some empirical data ...
Running 50,000,000 searches in a dictionary with 10,000 entries and comparing relative times to complete:
.. if each search succeeded:
- direct (unchecked) startup takes 1.2 seconds.
- A delayed (ContainsKey) start takes 2 seconds.
- Running processed (try-catch) takes 1.21 seconds.
.. if 1 out of every 10,000 requests does not work:
- A delayed (ContainsKey) start takes 2 seconds.
- Running processed (try-catch) takes 1.37 seconds.
.. if 16 out of every 10,000 requests fail:
- A delayed (ContainsKey) start takes 2 seconds.
- Running processed (try-catch) takes 3.27 seconds.
.. If out of every 10,000 requests, 250 of them fail:
- A delayed (ContainsKey) start takes 2 seconds.
- Running processed (try-catch) takes 32 seconds.
.. therefore, the protected test will add constant overhead and nothing more, and the try-catch test will work almost as fast as without a test if it never works, but it kills the performance in proportion to the number of failures.
The code I used to run the tests:
using System; using System.Collections.Generic; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Test(0); Test(1); Test(16); Test(250); } private static void Test(int failsPerSet) { Dictionary<int, bool> items = new Dictionary<int,bool>(); for(int i = 0; i < 10000; i++) if(i >= failsPerSet) items[i] = true; if(failsPerSet == 0) RawLookup(items, failsPerSet); GuardedLookup(items, failsPerSet); CaughtLookup(items, failsPerSet); } private static void RawLookup ( Dictionary<int, bool> items , int failsPerSet ){ int found = 0; DateTime start ; Console.Write("Raw ("); Console.Write(failsPerSet); Console.Write("): "); start = DateTime.Now; for(int i = 0; i < 50000000; i++) { int pick = i % 10000; if(items[pick]) found++; } Console.WriteLine(DateTime.Now - start); } private static void GuardedLookup ( Dictionary<int, bool> items , int failsPerSet ){ int found = 0; DateTime start ; Console.Write("Guarded ("); Console.Write(failsPerSet); Console.Write("): "); start = DateTime.Now; for(int i = 0; i < 50000000; i++) { int pick = i % 10000; if(items.ContainsKey(pick)) if(items[pick]) found++; } Console.WriteLine(DateTime.Now - start); } private static void CaughtLookup ( Dictionary<int, bool> items , int failsPerSet ){ int found = 0; DateTime start ; Console.Write("Caught ("); Console.Write(failsPerSet); Console.Write("): "); start = DateTime.Now; for(int i = 0; i < 50000000; i++) { int pick = i % 10000; try { if(items[pick]) found++; } catch { } } Console.WriteLine(DateTime.Now - start); } } }
Eliott
source share