delete vs undefined vs null (v49)

Revision 49 of this benchmark created on


Description

The delete operator removes a property entirely. Setting a property to null or undefined just changes the value of the key.

Assinging null/undefined is not equivalent to delete since the property can still be enumerated via a for-in loop, Object.keys, Object.getOwnPropertyNames, etc. but in practice they are often used to mean the same thing: that a property is unset.

Using 'delete' is conceptually preferable but the big problem is how the JavaScript engine chooses to react to "delete". JS Engines use "hidden classes" (Shapes) to optimise the code but "delete" supposedly downgrades from a Shape to a hash table which makes every property access significantly slower. To test if this is what actually happens or not, we compare accessing an object's properties after setting to null/undefined vs accessing after deleting to see if the Shape is lost or not (performance for accessing properties got worse).

Preparation HTML

<script>
  'use strict';
  var template = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
    g: 7,
    h: 8,
    i: 9,
    j: '10',
    k: 11,
    l: '12',
    m: function() {
      return 13;
    },
    n: 14,
    o: function() {
      return '15';
    }
  };
  var dump, log = function() {
      dump = arguments;
      };
</script>

Setup

var o = {};
    for (var x in template) {
      o[x] = template[x];
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Baseline (no modification)
log(o.j + o.l + o.o(), o.m());
ready
Setting properties to null
o.a = null;
o.i = null;
o.d = null;
o.f = null;
log(o.j + o.l + o.o(), o.m());
ready
Setting properties to undefined
o.a = undefined;
o.i = undefined;
o.d = undefined;
o.f = undefined;
log(o.j + o.l + o.o(), o.m());
ready
Deleting properties
delete o.a;
delete o.i;
delete o.d;
delete o.f;
log(o.j + o.l + o.o(), o.m());
ready
Setting properties to undefined + enumerable set to false
Object.defineProperties(o, {
  "a": {
      value: undefined,
      enumerable: false
  },
  "i": {
      value: undefined,
      enumerable: false
  },
  "d": {
      value: undefined,
      enumerable: false
  },
  "f": {
      value: undefined,
      enumerable: false
  }
});
log(o.j + o.l + o.o(), o.m());
ready

Revisions

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