Skip to content

Instantly share code, notes, and snippets.

@rekosko
Created May 8, 2014 08:41
Show Gist options
  • Save rekosko/999e58dc95ba3e4fc678 to your computer and use it in GitHub Desktop.
Save rekosko/999e58dc95ba3e4fc678 to your computer and use it in GitHub Desktop.
Performance Test for: array, list and dictionary
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace WorkPlace
{
class Program
{
private const int _collectionSize = 1000000;
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
Random random = new Random();
int index = random.Next(1, _collectionSize);
Console.WriteLine("All collections are type of `int`");
Console.WriteLine("Maximum collection size: {0}", _collectionSize);
Console.WriteLine("Random generated index used for value lookup: {0}\n", index);
#region array
stopwatch.Start();
var array = ArrayTest();
stopwatch.Stop();
Console.WriteLine("Array populating time elapsed: {0}", stopwatch.Elapsed);
stopwatch.Restart();
int lookupValue = array[index];
stopwatch.Stop();
Console.WriteLine("Array lookup time elapsed: {0}", stopwatch.Elapsed);
Console.WriteLine("Size: {0} bytes", GetObjectSize(array));
#endregion
Console.WriteLine("==============");
#region list
stopwatch.Restart();
var list = ListTest();
stopwatch.Stop();
Console.WriteLine("List populating time elapsed: {0}", stopwatch.Elapsed);
stopwatch.Restart();
lookupValue = list[index];
stopwatch.Stop();
Console.WriteLine("List lookup time elapsed: {0}", stopwatch.Elapsed);
Console.WriteLine("Size: {0} bytes", GetObjectSize(list));
#endregion
Console.WriteLine("==============");
#region dictionary
stopwatch.Restart();
var dictionary = DictionaryTest();
stopwatch.Stop();
Console.WriteLine("Dictionary populating time elapsed: {0}", stopwatch.Elapsed);
stopwatch.Restart();
lookupValue = dictionary[index];
stopwatch.Stop();
Console.WriteLine("Dictionary lookup time elapsed: {0}", stopwatch.Elapsed);
Console.WriteLine("Size: {0} bytes", GetObjectSize(dictionary));
#endregion
}
static int GetObjectSize(object obj)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream();
byte[] array;
binaryFormatter.Serialize(memoryStream, obj);
array = memoryStream.ToArray();
return array.Length;
}
static int[] ArrayTest()
{
var array = new int[_collectionSize];
for (int i = 0; i < _collectionSize; i++)
{
array[i] = i;
}
return array;
}
static List<int> ListTest()
{
var list = new List<int>();
for (int i = 0; i < _collectionSize; i++)
{
list.Add(i);
}
return list;
}
static Dictionary<int, int> DictionaryTest()
{
var dictionary = new Dictionary<int, int>();
for (int i = 0; i < _collectionSize; i++)
{
dictionary.Add(i, i);
}
return dictionary;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment