0

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.

user4704857
  • 469
  • 4
  • 18
  • 1
    1) What do you use for hash tables? Maps? 2) Is it possible to make list of keys before creating the map? – Pavel Oganesyan Oct 31 '17 at 09:44
  • The nature of my problem is iterative, I mean at some point I solve the problem X and maybe in 100 iterations next I need to solve the problem X again. So by hash table I would like to reduce computational complexity. Unfortunately, during the iterations I reach to keys and values, then I have no prior knowledge. – user4704857 Oct 31 '17 at 22:46

1 Answers1

1

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

Yair Altman
  • 5,704
  • 31
  • 34
  • Thanks for your answer. Is not searching keys in a cell array computationally expensive? BTW, I give java.util.Hashtable a try and let you know the result. – user4704857 Oct 31 '17 at 22:48
  • 1
    If you search the cell array in a vectorized manner (e.g., using `strcmp`) then this will be super-fast – Yair Altman Oct 31 '17 at 23:34
  • Thanks for your suggestion. I just implemented java.util.Hashtable and profiled the code. Seems that there is not much difference at least in small size problems. I will try cell array too. Thanks again. – user4704857 Nov 01 '17 at 00:29