Create a gist now

Instantly share code, notes, and snippets.

Making Javascript faster

Making Javascript faster


Profile before optimizing



IIFEs vs. nested functions

Seen nested functions like this before?

function doSomething(arg1, arg2) {
  function nestedHelper(arg) {
    return process(arg);

  return nestedHelper(arg1) + nestedHelper(arg2);

Unfortunately, every time you run the doSomething function, it recreates the nestedHelper function. Instead, you should do this:

var iife = (function() {
  function privateHelper(arg) {
    var result = process(arg);
    return result;

  return function(arg1, arg2) {
    return privateHelper(arg1) + privateHelper(arg2);

In this case, privateHelper is created only once.


Don't use arguments

As with above, using arguments makes your function variadic, which Javascript engines can't do much about.


However, don't think that an array parameter is any better (i.e. function(arrayParameter) { ... }). Between iterating arguments vs. an array parameter, arguments is faster.


Write shorter functions

If V8 sees that your function is short, it's more likely to be inlined. So don't fear splitting a large function into many smaller functions.

Evidence of optimizations in V8 can be seen by running this benchmark (notice the variation in IIFE running performance).


Put comments outside the function

You should be aware that comments inside your function increase the likelihood it won't get inlined. Strange, but true! I suppose that is the fate of super-optimized VMs.

However, this shouldn't be a problem at all if you minify your code, right? :-)


Use that instead of bind

It's much faster to create a variable in the outer scope rather than using Function.bind.

// bind - don't do this
function thisFunction() {
  return this.member;
var boundFunction = someFunction.bind(this);

// that - do this!
var that = object;
function thatFunction() {
  return that.member;


Don't add new members to constructor instances


function Point(x, y) {
  this.x = x;
  this.y = y;
var p1 = new Point(11, 22);
var p2 = new Point(33, 44);
p2.z = 55;

Always initialize object members in the same order



Prefer monomorphic over polymorphic functions


function add(x, y) {
  return x + y;


Avoid using delete


var o = { x: 1 }; 
delete o.x; // true 
o.x; // undefined

Use DocumentFragment


Web workers

TODO: give example of moving processing to another thread

TODO: Shims?

Use hash lookups instead of testing array presence


Little wins

Below are some of the other experiments I performed. They weren't included in the above list because the wins are fairly marginal.

No wins



Uint32Array vs Array is now significantly faster in Chrome. No difference in Firefox, and slower in IE though.


Array is faster by a bit (38% firefox 35, 6-9% chrome 44 & canary 46) for functions over using the arguments object

e-cloud commented Jun 13, 2016

@khoomeister, is down, could you post your test code?
