I am currently doing some tests on F# maps vs C# dictionaries. I realize they are quite different implementation wise but they do fill the same sort of use for their respective languages.
I have designed a simple test to check the insertion times due to the F# map being immutable thus it has to create an entirely new map for each insertion. I was wondering just how much of a hit that is.
Test is as follows:
//F#
module Test =
let testMapInsert () =
let sw = Stopwatch()
let rec fillMap endIdx curr map =
if curr = endIdx then
map
else
fillMap endIdx (curr + 1) (map |> Map.add curr curr)
sw.Start ()
let q = fillMap 100000000 Map.empty
sw.Stop ()
printfn "%A" sw.ElapsedMilliseconds
//C#
class Program
{
static void Test(int x) {
var d = new Dictionary<int,int>();
for (int i = 0; i < x; i++) {
d.Add(i,i);
}
}
static void Main(string[] args) {
Stopwatch sw = new Stopwatch();
sw.Start();
Test(10000000);
sw.Stop();
System.Console.WriteLine(sw.ElapsedMilliseconds);
//FSHARP.Test.testMapInsert(); f# function called in c#.
}
}
Doing 10 million element insertions with this yields the following times measured in ms:
C#: 332
F#: 13605
I figured the C# dictionary would be a fair bit faster but that is quite the difference.
Is there a way to speed up the F# dictionary for this sort of use-case? Or is this just the way it is and the F# map has a trade-off with performance in these situations for thread safety?