delete v. _.omit

JavaScript performance comparison

Test case created by Aaron

Info

In my Backbone application I'm receiving data from the server and modify it in a model's parse method as the return value of the parse method is what the Backbone Model will turn into the attributes. While almost all of the keys should become attributes, there is one that should not.

Previously I was deleteing that value from the response object passed to the parse method. I've been told that delete in JavaScript is an expensive operation. The other options would be to use underscore's omit method which I know creates a new object and copies keys and values over. I decided to find out which is more performant.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
delete
var obj = {
  key: 'value'
};
delete obj.key;
return obj;
pending…
_.omit
var obj = {
  key: 'value'
};
return _.omit(obj, 'key');
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

4 comments

Aaron (revision owner) commented :

Soooooo delete by a landslide :D

John-David Dalton commented :

Not really the same thing. delete mutates the actual object, while _.omit returns a new object.

Also since delete mutates the actual object, the property is removed on the very first iteration so the thousands after are not really doing much :P

Aaron (revision owner) commented :

I was able to confirm that jsperf doesn't create a new object for each iteration of the test. I modified it so that it has a fresh object each time. I also clarified my usage and why these two methods were being compared since they do function very differently.

John-David Dalton commented :

@Aaron Cool.

I've been told that delete in JavaScript is an expensive operation.

At the language nitty gritty yes, it may also de-opt the object for its lifetime but that's probably a micro-issue. You are right that this language level operation will beat a heavier handed utility method.

Add a comment