C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Properties: There are 2 properties called ArrayTest and DictionaryTest that return the data structures.
PropertyImportant: In this specific case, the two collections have basically the same purpose and usage.
Info: This code creates an array and a Dictionary that both contain strings corresponding to the keys or offsets 0-999.
And: The program finds that the values of the strings at the 100 key or offset are equal.
C# program that uses array, Dictionary
using System;
using System.Diagnostics;
using System.Collections.Generic;
class Program
{
static string[] ArrayTest
{
get
{
string[] array = new string[1000];
for (int i = 0; i < 1000; i++)
{
array[i] = i.ToString();
}
return array;
}
}
static Dictionary<int, string> DictionaryTest
{
get
{
var dictionary = new Dictionary<int, string>();
for (int i = 0; i < 1000; i++)
{
dictionary.Add(i, i.ToString());
}
return dictionary;
}
}
static void Main()
{
//
// Get the array and Dictionary.
//
var array = ArrayTest;
var dictionary = DictionaryTest;
//
// Lookup a value at this index and compare.
//
string value1 = array[100];
string value2 = dictionary[100];
Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(value1 == value2);
}
}
Output
100
100
True
Also: This article can point you in the direction of how you can exchange a Dictionary for an array.
BenchmarkCode that uses array and Dictionary: C#
// Array block
string value = array[i % 1000];
if (string.IsNullOrEmpty(value))
{
throw new Exception();
}
// Dictionary block
string value = dictionary[i % 1000];
if (string.IsNullOrEmpty(value))
{
throw new Exception();
}
Benchmark description
Iterations tested: 100000000
Loop type: for loop
Array lookup: 367 ms
Dictionary lookup: 2419 ms
Often: We can assign static resources such as images or files to a certain numeric value.
Then: We can store these static resources in an array instead of a Dictionary with int keys.