Advertisement
Guest User

Convert vs TryParse test

a guest
Jan 13th, 2013
688
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Collections.Generic;
  4.  
  5. namespace Test
  6. {
  7.     class MainClass
  8.     {
  9.         public static void Main(string[] args)
  10.         {
  11.             Random r = new Random();
  12.  
  13.             List<string> list = new List<string>();
  14.             for (int i = 0; i < 1000000; ++i)
  15.             {
  16.                 string listItem = "";
  17.                 for (int j = 0; j < 4; ++j)
  18.                 {
  19.                     listItem += r.Next(10).ToString();
  20.                 }
  21.  
  22.                 int index;
  23.                 if ((index = r.Next(2)) == 0)
  24.                 {
  25.                     listItem = listItem.Replace(listItem [index], (char)(r.Next(short.MaxValue - 20) + 20));
  26.                 }
  27.  
  28.                 list.Add(listItem);
  29.             }
  30.  
  31.             Stopwatch sw = new Stopwatch();
  32.  
  33.             sw.Start();
  34.             {
  35.                 int dummy = 0;
  36.                 for (int i = 0; i < list.Count; ++i)
  37.                 {
  38.                     string str = list [i];
  39.                     try
  40.                     {
  41.                         Convert.ToInt32(str);
  42.                         ++dummy;
  43.                     } catch
  44.                     {
  45.                         --dummy;
  46.                     }
  47.                 }
  48.             }
  49.             sw.Stop();
  50.  
  51.             long method1 = sw.ElapsedMilliseconds;
  52.  
  53.             sw.Reset();
  54.             sw.Start();
  55.             {
  56.                 int dummy = 0;
  57.                 for (int i = 0; i < list.Count; ++i)
  58.                 {
  59.                     string str = list [i];
  60.                     int output;
  61.                     if (int.TryParse(str, out output))
  62.                     {
  63.                         ++dummy;
  64.                     }
  65.                     else
  66.                     {
  67.                         --dummy;
  68.                     }
  69.                 }
  70.             }
  71.             sw.Stop();
  72.  
  73.             long method2 = sw.ElapsedMilliseconds;
  74.  
  75.             Console.WriteLine("METHOD 1: {0}", method1);
  76.             Console.WriteLine("METHOD 2: {0}", method2);
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement