using System.Collections.Generic;
using System.Diagnostics;
const int iterations = 1000;
private static void Benchmark(string name, Action act)
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
Console.WriteLine(name + ": " + (sw.ElapsedTicks).ToString());
private static int CountInObjects(object[] objects) {
foreach (object o in objects) {
private static int CountInDict(Dictionary<int, object> dict) {
foreach (KeyValuePair<int, object> pair in dict) {
public static void Main(string[] args)
Random rng = new Random();
object[] objects = new object[10000];
for (int i = 0; i < objects.Length; i++) {
case 0: objects[i] = new A(); break;
case 1: objects[i] = new B(); break;
case 2: objects[i] = new C(); break;
Dictionary<int, object> dict = new Dictionary<int, object>();
for (int i = 0; i < objects.Length; i++) {
Benchmark("cast", () => useInt += CountInObjects(objects));
Benchmark("lookup", () => useInt += CountInDict(dict));
Console.WriteLine("\n\nignore me: " + useInt.ToString());