matlabhashpre-allocation

MATLAB: Growing hash table


I use a hash table in my code and when the code is running I add keys and values into the hash table. At first, I thought using a hash table make my code faster but I was wrong and using hash table has made it slower. As I searched about it, I realized that increasing size of the hash table and writing it takes time because when it gets larger, MATLAB seeks for a bigger space and seeking for a bigger space wastes time.

Is there any preallocating method for hash tables in MATLAB?

Thanks.


Solution

  • I assume you mean that you're using the built-in containers.Map object as your hashtable. While there is no direct means to pre-allocate such an object, I suggest that you use either a simple two-column cell-array, or a java.util.Hashtable object, both of which are much faster in general than containers.Map.

    Reference: https://undocumentedmatlab.com/blog/using-java-collections-in-matlab