The JavaScript blog.


graphics optimisation angularjs

Angular Selection Model, Normalized Particle Swarm Optimization

Posted on .

Angular Selection Model

Angular Selection Model (GitHub: jtrussell / angular-selection-model, License: MIT) by Justin Russell is an AngularJS directive for managing selections of items in lists and tables. It's indifferent to how data is presented, and only tracks what items are selected.

This example allows a text input to filter a list of items, and also allow the user to select items from the list:

<input type="text" ng-model="fancyfilter" />

  <tr ng-repeat="item in fancy.bag | filter:fancyfilter"
    <td><input type="checkbox"></td>

The directive does a lot of things behind the scenes to make this work naturally. An internal read-only list is used to represent selected items, and there's a provider for setting things like the selected attribute and class name assigned to selected items at a global level. Checkboxes are automatically managed, including support for multiple selection.

Justin has included tests, documentation, and examples.

Normalized Particle Swarm Optimization

Swarm optimisation

Adrian Seeley sent in this gist: JavaScript Normalized Particle Swarm Optimization Implementation. If you want to try it, just click "Download Gist" then open the HTML file locally.

The reason I wanted to write about it was he decided to license it as "Abandoned", so rather than letting it languish I thought I'd share it in case someone finds it useful.

Here's how Adrian described the project:

Particle swarm optimization is an incredibly viable machine learning structure, but is often implemented using database oriented designs splayed across multiple files in c++ or java making it very inaccessible to newcomers. I present a simple, unoptimized, and easy to follow javascript implementation of normalized particle swarm optimization, making use of full descriptive variable names entirely encapsulated in a single inlined function.


search optimisation productivity angularjs

Grasp, Optimizing AngularJS

Posted on .


George Zahariev sent in his latest project, Grasp (GitHub: gkz / grasp, License: MIT, npm: grasp). Grasp allows you to search and replace JavaScript code based on its abstract syntax tree.

Unlike programs such as "grep" or "sed", it searches the structure behind your code, rather than simply the text you've written - this allows for much more powerful searches.

It uses a language inspired by CSS selectors for creating intuitive search expressions. For example, given this code:

var obj = {  
  toEven: function(x) {
    if (isEven(x)) {
      return x;
    } else {
      return x + 1;

assert.equal(false, isEven(7));  

Searching for obj.props func! #isEven would match the call to isEven inside the property toEven on the object obj. References outside, like the assertion at the bottom, will not be matched.

My preferred solution for searching code is The Silver Searcher, but I like the idea of combining an AST with search and replace -- it seems like a potentially fertile ground for experimentation.

Optimizing AngularJS: 1200ms to 35ms

In Optimizing AngularJS: 1200ms to 35ms, optimisations for AngularJS are discussed. It's actually a lot deeper than you might expect: it goes from caching DOM elements to bypassing watchers for hidden elements, and deferring element creation:

A straightforward AngularJS implementation of the log view took 1.2 seconds to advance to the next page, but with some careful optimizations we were able to reduce that to 35 milliseconds. These optimizations proved to be useful in other parts of the application, and fit in well with the AngularJS philosophy, though we had to break few rules to implement them. In this article, we'll discuss the techniques we used.

The conventional wisdom for AngularJS says that you should keep the number of data-bound elements below 200. With an element per word, we were far above that level.

Using Chrome's JavaScript profiler, we quickly identified two sources of lag. First, each update spent a lot of time creating and destroying DOM elements. Second, each word had its own change watcher, which AngularJS would invoke on every mouse click. This was causing the lag on unrelated actions like the navigation dropdown.

The post got a huge amount of interest, so the authors are working on open sourcing their AngularJS directives.


tutorials frameworks lmaf optimisation

Client-Side Benchmarks

Posted on .

*Let's Make a Framework* is an ongoing series about building a JavaScript framework from the ground up. These articles are tagged with [lmaf](http://dailyjs.com/tags.html#lmaf). The project we're creating is called [Turing](http://github.com/alexyoung/turing.js). Documentation is available at [turingjs.com](http://turingjs.com/).

Last week we had a very interesting discussion about optimising the
deceptively simple hasClass function that I wrote for
Turing's DOM module. Not only is optimisation difficult, once you bring
browsers into the mix it can seem like a dark art. Particularly when
cross-browser issues are taken into account, which is why I've covered
things like cached browser feature detection in previous tutorials.

I mentioned that we really needed client-side benchmarks to talk
confidently about performance, because my benchmark example script was
just intended to be used in Node. As I already used
Benchmark.js (GitHub: bestiejs / benchmark.js, License: MIT,
npm: benchmark) I've used it again for browser benchmarks. And guess
what? It even works in IE6!

Writing Browser Benchmarks

I've added benchmark "latest" to the
devDependencies in the
package.json file. Then, at the bottom of a HTML test harness file, I added a script
tag to load Benchmark.js.

Next I wrote a pure JavaScript file for the DOM-related benchmarks and
added it to the other script tags:

var suite = new Benchmark.Suite,
    div = $t('#test-div')[0],
    cache = {};

function log(text) {
  $t('#results').append('' + text + '');

function hasClassRegExp(element, className) {
  if (element.className && element.className.length) {
    return new RegExp('(^|\\s)' + className + '($|\\s)').test(element.className);
  } else {
    return false;

function hasClassCachedRegExp(element, className) {
  if (!cache[className]) {
    cache[className] = new RegExp('(^|\\s)' + className + '($|\\s)');
  if (element.className && element.className.length) {
    return cache[className].test(element.className);
  } else {
    return false;

suite.add('hasClassRegExp', function() {
  hasClassRegExp(div, 'example1');
  hasClassRegExp(div, 'unknown');
.add('hasClassCachedRegExp', function() {
  hasClassCachedRegExp(div, 'example1');
  hasClassCachedRegExp(div, 'unknown');
.add('built-in', function() {
  turing.dom.hasClass(div, 'example1');
  turing.dom.hasClass(div, 'unknown');
.on('cycle', function(event, bench) {
.on('complete', function() {
  log('Fastest is ' + this.filter('fastest').pluck('name'));

Benchmark.js uses callbacks and events to organise benchmarks. That
means you need to instantiate a suite using var suite = new
, then add benchmarks using
suite.add('name', function() {}). It allows chaining, so as
you can see I've added a few benchmarks and then watched for two events,
cycle and complete. The cycle
event will run after each benchmark. Easy!

I'm using the \$t Turing alias to do some simple DOM
manipulation for displaying results. The log function could
actually be placed in a benchmark helpers file once more benchmarks have
been added. Just out of interest, I kept the old simple
hasClass functions and also included the one currently
implemented in turing.dom.hasClass.

This benchmark also includes hasClassCachedRegExp. I
noticed that Zepto caches regexes,
and it turns out this performs extremely well in Firefox and Chrome, but
not so well in IE6. However, remember that when comparing the built-in
function, you might be looking at element.classList
depending on the browser. In Firefox, Ryan Cannon's
String.prototype.indexOf solution performs better than

Given that each browser appears to have different performance
characteristics, should we use different functions? I'd probably never
do this, unless I was targeting a specific browser. This might sound
unusual, but plenty of people are developing games that can only run in
WebKit mobile browsers (and Zepto specifically targets WebKit).


Chrome 13, Mac:

Firefox 6, Mac:

Internet Explorer 6, Windows XP, VirtualBoxVM:


If you're working on client-side code, it doesn't take much work to be
scientific about benchmarks. And, using Node and npm to manage your
tools can make it quick to set things up. When writing optimised code,
don't champion a given solution -- be scientific, experiment, and try to
discover the solution most suited to the task at hand. In the interest
of science, benchmarks like these should be run on a wide range of
machines (not just virtual machines, but I use those purely for

This code can be found in commit


tutorials frameworks lmaf optimisation

Let's Make a Framework: hasClass Optimisation

Posted on .

*Let's Make a Framework* is an ongoing series about building a JavaScript framework from the ground up. These articles are tagged with [lmaf](http://dailyjs.com/tags.html#lmaf). The project we're creating is called [Turing](http://github.com/alexyoung/turing.js). Documentation is available at [turingjs.com](http://turingjs.com/).

Last week I explained how a simple hasClass implementation might work for detecting
CSS classes, complete with tests and suitable documentation. Henrik
wrote a comment with some code that he
claimed was faster. If you're building your own open source project it's
likely that people may post their own performance suggestions and
patches. This should be managed with care, because overly aggressive
optimisation can potentially lead to confusing code or unexpected bugs.

In this tutorial I'm going to walk through Henrik's code as I would any
optimisation suggestion, using a little bit of science in the form of
tests and benchmarks.

The Original hasClass

The original code is based around a regular expression. Like most of my
tutorial code, I've attempted to make it extremely explicit and easy to

dom.hasClass = function(element, className) {
  if (!className || typeof className !== 'string') return false;
  if (element.nodeType !== nodeTypes.ELEMENT_NODE) return false;
  if (element.className && element.className.length) {
    return new RegExp('(^|\\s)' + className + '($|\\s)').test(element.className);
  } else {
    return false;

The Optimised hasClass

This is Henrik's code:

function hasClassString(e, c) {
  var s = e.className, i = s.indexOf(c);
  return i != -1 && (s.charCodeAt(i - 1) || 32) == 32 && (s.charCodeAt(i + c.length) || 32) == 32;

The first line gets the class name from the element and finds the index
of the class name that we're looking for using indexOf.

The second line is longer. The comparison with -1 is done
as early as possible to optimise cases where the class name hasn't been
found. The next part checks to see if the character before the match is
a space (32 is the character code for space). When the index is outside
the string, charCodeAt will return 32 using the
|| because NaN will be returned:

// NaN

''.charCodeAt(0) || 32
// 32

'a'.charCodeAt(0) || 32
// 97

The same thing is true for the end of the line, which the part after
&& deals with.

It looks like this code makes sense, but is it really faster?


To benchmark these functions, I used
Benchmark.js to compare the performance of each:

var Benchmark = require('benchmark')
  , suite = new Benchmark.Suite
  , div = { className: 'example1 example2 example3' };

function hasClassString(e, c) {
  var s = e.className, i = s.indexOf(c);
  return i != -1 && (s.charCodeAt(i - 1) || 32) == 32 && (s.charCodeAt(i + c.length) || 32) == 32;

function hasClassRegExp(element, className) {
  if (element.className && element.className.length) {
    return new RegExp('(^|\\s)' + className + '($|\\s)').test(element.className);
  } else {
    return false;

suite.add('hasClassString', function() {
  hasClassString(div, 'example1');
  hasClassString(div, 'example2');
  hasClassString(div, 'example3');
  hasClassString(div, 'unknown');
.add('hasClassRegExp', function() {
  hasClassRegExp(div, 'example1');
  hasClassRegExp(div, 'example2');
  hasClassRegExp(div, 'example3');
  hasClassRegExp(div, 'unknown');
.on('cycle', function(event, bench) {
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').pluck('name'));
// run async

The results on my machine look like this:

hasClassString x 2,319,886 ops/sec ±0.27% (81 runs sampled)
hasClassRegExp x 17,348 ops/sec ±0.39% (81 runs sampled)

The indexOf/charCodeAt version appears to perform over 100
times faster!


I dropped the optimised code into the DOM module:

 * Detects if a class is present, optimised by Henrik Lindqvist.
 * @param {Object} element A DOM element
 * @param {String} className The class name
 * @return {Boolean}
dom.hasClass = function(element, className) {
  if (!className || typeof className !== 'string') return false;
  if (element.nodeType !== nodeTypes.ELEMENT_NODE) return false;
  var s = element.className, i = s.indexOf(className);
  return i != -1 && (s.charCodeAt(i - 1) || 32) == 32 && (s.charCodeAt(i + className.length) || 32) == 32;

Then I ran the tests in IE6, 7, 8, Firefox 4, Chrome, Safari, and gave
up because it seemed fine. That's not to say my tests are perfect,
however, but it seems Henrik's code does what we want.

Managing Optimisation

When it comes to optimising code, you're only as good as your benchmarks
and tests. There's also the question of whether optimisation is really
useful. In this case, hasClass is a good candidate for
optimisation because it's likely to be used frequently by client-side
developers. There are times where regular expressions won't perform as
well as direct string manipulation, but will yield more succinct code. I
found Henrik's code easy to follow and the performance improvement was
huge, so this seems clear cut to me.

The new code should have proper client-side benchmarks, but I'll save
that for another week.

This week's latest commit was

[Update] Reader Feedback

Ryan Cannon suggested this:

dom.hasClass = function(element, className) {
  return (' ' + element.className + ' ').indexOf(' ' + className + ' ') !== -1;

It's slightly slower than Henrik's suggestion, but it fixes a problem I
didn't spot that Adam Solove pointed out:

Given a div with the classes: "something some" and a query for the class "some", this code returns false when it should return true. The first match of a substring isn't followed with a space, but you need to repeatedly look for the same substring in case it occurs by itself later.

I forgot to include coverage of
element.classList again, so I've added that as well:

if (turing.detect('classList')) {
  dom.hasClass = function(element, className) {
    return element.classList.contains(className);
} else {
  dom.hasClass = function(element, className) {
    return (' ' + element.className + ' ').indexOf(' ' + className + ' ') !== -1;

Recall that turing.detect will cache the result and first
requires turing.addDetectionTest to work. In this case it's
only called once.

I've added the readers that suggested these improvements to the
contributor list in Turing's README.