What is the best way (from perspective of speed/memory) to get OrderedMap element by index? Is it map.toArray(index)? If yes what is the cost of this operation?
Is
Sequences are wrappers around Collections, that allow lazy access to the underlying data. They have to instantiate a tiny wrapper class, but it needs almost no memory.
The complexity of this operation is O(1).
To get access to the API for ordered collection, just use map.toIndexedSeq().get(index) or map.valueSeq().get(index);.
map.toArray(index) is an expensive operation, as it converts the whole immutable to a native javascript array. It's complexity is at least O(n).
function valueSeq(coll, searchVal) {
  return coll.valueSeq().get(searchVal);
}
function indexedSeq(coll, searchVal) {
  return coll.toIndexedSeq().get(searchVal);
}
function toArray(coll, searchVal) {
  return coll.toArray()[searchVal];
}
function toList(coll, searchVal) {
  return coll.toList().get(searchVal);
}
function arrayRange(len) {
  return new Array(len).fill(null).map((_, i) => `thing ${i}`);
}
function timeGet(checkWhat, coll, find, iters) {
  let startTime = performance.now();
  let size = coll.length || coll.size;
  for (let i = 1; i < iters; i++) {
    let searchVal = i % coll.size,
      result = find(coll, searchVal);
      if(result != `thing ${searchVal}`){
        console.log('fail', searchVal, `"${result}"`);
      }
  }
  return Math.floor(performance.now() - startTime);
}
const MIN_LEN = 10,
  MAX_LEN = 1e4,
  ITERS = 2000;
  
console.log('\t\t\tindexedSeq\ttoArray\t\ttoList\t\tkeyedSeq');
for (let len = MIN_LEN; len <= MAX_LEN; len *= 10) {
  const immutOrderedSetRange = Immutable.OrderedSet(arrayRange(len));
  console.log(`${len}\t\t\t` +
    `${timeGet('indexedSeq', immutOrderedSetRange, indexedSeq, ITERS)}\t\t` +
    `${timeGet('toArray', immutOrderedSetRange, toArray, ITERS)}\t\t` +
    `${timeGet('toList', immutOrderedSetRange, toList, ITERS)}\t\t` +
    `${timeGet('valueSeq', immutOrderedSetRange, valueSeq, ITERS)}`)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.12/immutable.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With