Dictionaries Performance?

Godot Version

4.2.1

Question

I’m just wondering how efficient running the .has() method on a dictionary with up to 8,000 entries would be. Would this be slow? It would be ran many times per second as well, so this is something where performance definitely matters.

It depends a lot on the size of the dictionary. In the worst case scenario, the thing you are looking for with .has() does not exist, and that .has() will need to check every single entry in the dictionary.

How much will that impact performance? The best thing you can do is to play the game with and without those .has() calls and see how much of a performance it takes on your particular project.

Check the source code

Since Godot is open source, you can also check what .has() do:
github.com/godotengine/godot/blob/master/core/variant/dictionary.cpp

HashMap<Variant, Variant, VariantHasher, StringLikeVariantComparator> variant_map;

bool Dictionary::has(const Variant &p_key) const {
	return _p->variant_map.has(p_key);
}

Looks like it’s calling the method .has() in a HashMap:
godotengine/godot/blob/master/core/templates/hash_map.h#L308

_FORCE_INLINE_ bool has(const TKey &p_key) const {
	uint32_t _pos = 0;
	return _lookup_pos(p_key, _pos);
}

And finally, that .has() in HashMap is calling _lookup_pos() which you can also take a look at:
github.com/godotengine/godot/blob/master/core/templates/hash_map.h#L99

Basically every time you really want to know what is really going on under the hood, you can check the source code to really be sure!

1 Like