Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- namespace Test1
- {
- class A {
- public string text;
- }
- class B : A {
- }
- class C : A {
- public override bool Equals(object other)
- {
- return text==(other as C).text;
- }
- public override int GetHashCode()
- {
- return text.GetHashCode();
- }
- }
- class Program
- {
- private static Random random = new Random();
- public static string RandomString(int length)
- {
- const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- return new string(Enumerable.Repeat(chars, length)
- .Select(s => s[random.Next(s.Length)]).ToArray());
- }
- static void benchmark<T, N>(string label, List<T> listYes, List<N> listNo) where T : A where N: A{
- int ticks = Environment.TickCount;
- for (int i = 0; i < 1000; i++)
- {
- Dictionary<A, int> dict = new Dictionary<A, int>();
- foreach (T t in listYes)
- {
- dict.Add(t, 1);
- }
- foreach (N t in listNo)
- {
- if (dict.ContainsKey(t)) throw new Exception("oops!");
- }
- foreach (T t in listYes)
- {
- if (!dict.ContainsKey(t)) throw new Exception("oops!");
- }
- }
- Console.WriteLine(label+" took "+(Environment.TickCount-ticks) + "ms");
- }
- static void Main(string[] args)
- {
- Console.WriteLine("B{'xxx'}.HashCode = " + new B { text = "xxx" }.GetHashCode());
- Console.WriteLine("B{'xxx'}.HashCode = " + new B { text = "xxx" }.GetHashCode());
- Console.WriteLine("C{'xxx'}.HashCode = " + new C { text = "xxx" }.GetHashCode());
- Console.WriteLine("C{'xxx'}.HashCode = " + new C { text = "xxx" }.GetHashCode());
- List<string> items = new List<string>();
- for (int i = 0; i < 10000; i++) items.Add(RandomString(10));
- List<B> itemsB = new List<B>();
- foreach (string item in items) itemsB.Add(new B { text = item });
- List<C> itemsC = new List<C>();
- foreach (string item in items) itemsC.Add(new C { text = item });
- benchmark("B", itemsB, itemsC);
- benchmark("C", itemsC, itemsB);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment