Dealing with a simple dynamic array - page 2

 
JC:
... Also depends on the value being searched for. The example value in the above code - 49 - is fairly ideal for the array. Changing it to e.g. 1 means that the ArrayInt.Search() has to do much more work, and becomes slower, on my computer, than the hashtable at only about 25 items in the list.

Slightly more realistic example. Searches for each value in the array, plus a missing element (-1), instead of repeatedly using a fixed value.

On my computer, the hashtable then becomes more efficient at under 20 items, and this would again be weighted further in real life by the periodic need to re-sort the array because of additions.

#property strict

#include <hashtable-templated.mqh>
#include <arrays/ArrayInt.mqh>

input int   ArrayElements = 20;
input int   TestIterations = 100000;

void TestArray()
{
   CArrayInt arr;
   for (int i = 0; i < ArrayElements; i++) {
      arr.Add(i);
   }
   // Although array is already sorted, must be explicitly sorted or 
   // else Search() exits early with a negative result
   arr.Sort();
   
   ulong tmStart = GetMicrosecondCount();
   for (int i = 0; i < TestIterations; i++) {
      // Search for each existing element, plus one non-existent item (-1)
      for (int j = -1; j < ArrayElements; j++) {
         bool bTest = (arr.Search(j) >= 0);
      }
   }
   ulong tmEnd = GetMicrosecondCount();
   
   Print("Array method, microseconds taken: " , (tmEnd - tmStart));
}

void TestHashTable()
{
   BasicHashTable<int, int> bht;
   for (int i = 0; i < ArrayElements; i++) {
      bht.Set(i, i);
   }

   ulong tmStart = GetMicrosecondCount();
   for (int i = 0; i < TestIterations; i++) {
      // Search for each existing element, plus one non-existent item (-1)
      for (int j = -1; j < ArrayElements; j++) {
         bool bTest = bht.ContainsKey(j);
      }
   }
   ulong tmEnd = GetMicrosecondCount();
   
   Print("Hashtable method, microseconds taken: " , (tmEnd - tmStart));
}

void OnStart()
{
   TestArray();
   TestHashTable();
}
 
JC:
... Also depends on the value being searched for. The example value in the above code - 49 - is fairly ideal for the array. Changing it to e.g. 1 means that the ArrayInt.Search() has to do much more work, and becomes slower, on my computer, than the hashtable at only about 25 items in the list.

Which hash library are you using? link?
 
nicholishen:

Which hash library are you using? link?
See above
 
ZetaTrader: The compiler won't complain about the #include statement, but how would I declare my array as a cArray?

You said "what I'd call a pretty simple operation in other languages." If you know how classes such as C++'s Vector works in other languages, you wouldn't be asking that.

cArrayDouble Prices;
Prices.Add(...);
Reason: