Question

Elixir newbie here. This question will be short and sweet!

I am learning Elixir through doing online programming exercises and was given the following advice about a recent submission:

In general it's better to use Dict.foo instead of HashDict.foo if possible. Dict functions work with all kinds of dictionaries so if your code changes you'll have less places to update.

Which made me realise that I have no idea when you should use HashDict over Dict. What special virtues does one have?

Was it helpful?

Solution

HashDict's API matches Dict's API, because HashDict implements Dict.Behaviour. The recommendation to use Dict's API over HashDict's is because in general it's always a good idea to code against the interface instead of the implementation, where Dict in this case is the interface, and HashDict is an implementation of that interface.

I'm also not sure about Sasa's point regarding performance, it's possible that's a concern, but I'm almost 100% sure that in general you should be more concerned about how you are using a Dict, instead of how you are accessing it.

OTHER TIPS

The only use case I can think of is performance optimization. Dict functions need to resolve the target module in run-time, and then forward the call to that module. Calling HashDict directly overcomes this step.

Im sure that in vast majority of situations this difference won't matter. But if you have a case where every microsecond counts, and you perform frequent calls to Dict, you might gain some speed by calling HashDict directly. Personally, I'd measure before doing this.

So long story short, Dict should serve you in 99,9999999% of cases :-)

As far as I can see, now you should just use Map. Dict is deprecated as is HashDict

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top