Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * WARNING THIS IS A MICRO BENCHMARK!
- *
- * A responce to http://forum.unity3d.com/threads/90719-C-having-trouble-using-.find-on-a-List
- *
- * A NPSF3000 test.
- *
- * Conclusion - use what you want, don't microoptimise for the for version. Not only is it harder to read [for lamba fluet programmers] the performance in a 'typical' implementation is appalling.
- 27/11/11 - Q6600, Win7 64, .net 4.0
- Rough Results ('000 Its/Second)
- Iterations List.For For
- 1 180 100
- 100 750 120-180
- 10000 1000 120-180
- 1000000 1000 180 [Very consistant]
- *
- *
- [I did a quick test and cached the data.Count() in the For version. It boosted the 1Mn it result from 180 to 17000. So this doesn't prove that List.For is faster than For, but it does restate the need to either spend the LOC on performance [in this particular instance a waste], or go with the built in option. Going with for because it is faster without testing and optimisation can lead to poorer perfomance and maintanability!.]
- *
- */
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Diagnostics;
- namespace List_Dot_Find
- {
- class Program
- {
- static void Main(string[] args)
- {
- const int iterations = 1000000;
- var data = new List<MyClass>(200);
- for (var i = 0; i < 200; i++)
- data.Add(new MyClass(i, "Guest " + i));
- var rnd = new Random();
- while (true)
- {
- var sw1 = Stopwatch.StartNew();
- for (var i = 0; i < iterations; i++)
- {
- var findID = rnd.Next(200);
- data.Find(x => x.ID == findID);
- }
- sw1.Stop();
- var sw2 = Stopwatch.StartNew();
- for (var i = 0; i < iterations; i++)
- {
- var findID = rnd.Next(200);
- for (var x = 0; x < data.Count(); x++)
- if (data[x].ID == findID) break;
- }
- sw2.Stop();
- Console.WriteLine();
- Console.WriteLine("{0} iterations:", iterations);
- Console.WriteLine("List.Find: {0}/s", (iterations * Stopwatch.Frequency / sw1.ElapsedTicks ).ToString("N0"));
- Console.WriteLine("For : {0}/s", (iterations * Stopwatch.Frequency / sw2.ElapsedTicks).ToString("N0"));
- Console.WriteLine();
- Console.WriteLine();
- Console.ReadLine();
- }
- }
- }
- public class MyClass
- {
- public int ID
- {
- get { return _id; }
- }
- public string Name
- {
- get { return _name; }
- }
- private int _id;
- private string _name = string.Empty;
- // constructor
- public MyClass(int id, string name)
- {
- try
- {
- _id = ID;
- _name = name;
- }
- catch (Exception e)
- {
- Console.WriteLine("Error in MyClass Constructor1:" + e);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement