简体   繁体   中英

f# dictionary, immutability and performance

I am porting C# code to F# and I have a situation with some rather large, but simple dictionaries; they're value is a single float and the key is a string.

The code processes commands that require to insert, delete but also update some keys and there are a lot of operations happening constantly (it is tracking trading order books).

I'm quite new at F# and I'm trying to understand something. From what I read, the F# dictionaries are immutable, so any change would rebuild the dictionary.

If I have a dictionary with 1000 entries and I do 200 changes in it, does that mean that the dictionary's data gets rebuild 200 times?

If this is not the right collection, in F#, what else should I use for a quite large list that changes many times per second? (the data is [string] = float)

The System.Collections.Generic.Dictionary class is identical between F# and C# (it's the exact same thing). If that works for you in C#, it should work perfectly well for you in F#, using precisely the same method calls. This interoperability with other .NET languages is a good aspect of F#. F# for Fun and Profit has some info on porting from C# to F# .

The confusion likely arises because you are looking at discussions of F#'s built-in Map type , which does much the same thing but is F#-specific and 'immutable' (I'm pretty sure it is a persistent data structure , meaning that you don't have to entirely chuck out the old one to create a new version).

See here and here for a bit more of a Dictionary vs Map discussion - turns out there's actually C# dictionaries, F# dictionaries and F# maps, apparently.

All this being said, using strings as keys in a dictionary doesn't sound like a particularly great idea to me in performance terms, though I'm failing to come up with a suitable replacement if there is a potentially unbounded set of keys possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM