Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable.js: get map entity by index (not by key)

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

like image 266
VB_ Avatar asked Nov 10 '22 04:11

VB_


1 Answers

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>
like image 135
dube Avatar answered Nov 14 '22 22:11

dube