Ramda update and alternatives

Benchmark created on


Setup

// update utilizes always and adjust which utilizes _concat (to copy)
function _concat(set1, set2) {
  set1 = set1 || [];
  set2 = set2 || [];
  var idx;
  var len1 = set1.length;
  var len2 = set2.length;
  var result = [];

  idx = 0;
  while (idx < len1) {
    result[result.length] = set1[idx];
    idx += 1;
  }
  idx = 0;
  while (idx < len2) {
    result[result.length] = set2[idx];
    idx += 1;
  }
  return result;
}

function always(val) {
  return function() {
    return val;
  };
}

function adjust(idx, fn, list) {
  var len = list.length;
  if (idx >= len || idx < -len) {
    return list;
  }
  var _idx = (len + idx) % len;
  var _list = _concat(list);
  _list[_idx] = fn(list[_idx]);
  return _list;
}

function update(idx, x, list) {
  return adjust(idx, always(x), list);
}

// optimized to clone via concat and then mutate clone
function optimized(idx, x, list) {
  const cloned = [].concat(list)
  cloned[idx] = x;
  return cloned;
}

var arr = [];
for (i = 0; i < 1000; i++) {
  arr[i] = i;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Current
update(500, 0, arr);
ready
Optimized
optimized(500, 0, arr);
ready
Native Array#with
arr.with(500, 0);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.