Steve Bennett
Steve Bennett

Reputation: 126887

Is it faster to delete properties or construct a new object with only desired properties?

I have a loop being executed several million times, in NodeJS, that amongst many other things strips a few undesired properties from some objects.

I'm curious to know in general, whether it is faster to do:

undesiredPropsArray.forEach(p => delete(obj[p]))

or

var newObj = {};
Object.keys(obj).forEach(p => { if (!undesiredPropsObj[p]) newObj[p] = obj[p] });

Simply running a test isn't as simple as it sounds maybe, because the number of desired and undesired properties will vary.

Upvotes: 2

Views: 423

Answers (2)

bigless
bigless

Reputation: 3111

You can benchmark and compare javascript code on jsperf. I did and first approach is faster as expected (aprox by 66% - this may vary)..

EDIT: This is init code I used:

  var undesiredPropsArray = [];
  var undesiredPropsObj = {};
  var obj = {};

  for (i=0;i<10000;i++) {
    obj[i] = null;
    if ((i%2) === 0) {
        undesiredPropsArray.push(i);
        undesiredPropsObj[i] = null;
    }
  }

Upvotes: 1

Hari Lubovac
Hari Lubovac

Reputation: 106

If you, for a moment, assume that each of those commands take equal time to execute, then whichever task has less commands to execute will execute faster. In other words, if you have less undesired properties, compared to number of properties that you want to keep, then deleting should be faster (and vice-versa). Although, unless we're talking about huge objects processed a huge number of times, the time saved will be negligent. I think :)

Upvotes: 1

Related Questions