Advertisement
Guest User

Fixing the C# is slower the RealBasic myth...

a guest
Sep 9th, 2012
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.95 KB | None | 0 0
  1. // With reference to http://pastebin.com/f287a2609
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5.  
  6. namespace HashSpeed
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             // Fix #1 - You are filling a dictionary with 1000000 values -
  13.             // you better set up expectation with initial capacity
  14.             Dictionary<string, int> nDic = new Dictionary<string, int>(1000000);
  15.             int i;
  16.             int x;
  17.             Random rnd = new Random();
  18.             Int64 tTimer = DateTime.Now.Ticks;
  19.  
  20.             // Fix #2 - User StringBuilder rather than string concatenations
  21.             StringBuilder sb = new StringBuilder(16);
  22.             Char[] chrs = new Char[16];
  23.  
  24.             for (i = 1; i <= 1000000; i++)
  25.             {
  26.                 // Generate a random UUID                
  27.                 for (x = 1; x <= 16; x++)
  28.                 {
  29.                     // Fix #3 - No need to go via encoder, in C# int are cast-able to Char
  30.                     chrs[x - 1] = (Char)rnd.Next(0, 255);
  31.                 }
  32.  
  33.                 // Fix #4 - Better join all 16 chars in a single call
  34.                 String pUUID = sb.Clear().Append(chrs).ToString();
  35.  
  36.                 //Check if pUUID exists in the dictionary
  37.                 if (!nDic.ContainsKey(pUUID))
  38.                 {
  39.                     //If not, add it to the dictionary
  40.                     nDic.Add(pUUID, 0);
  41.                 }
  42.             }
  43.  
  44.             tTimer = DateTime.Now.Ticks - tTimer; //Stop the clock!
  45.             Console.WriteLine("Operation completed in " + ((double)tTimer / (double)TimeSpan.TicksPerSecond).ToString());
  46.             Console.WriteLine(nDic.Count.ToString() + " keys in dictionary");
  47.  
  48.             //Keep the window open at the end of the test
  49.             // Fix #5 - Doing a while(1); is not a good way to wait for the user to end the program...
  50.             Console.ReadKey();
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement