Posts tagged "optimization"

Efficient rounding in JavaScript

So you have some number, x, which you want to round to the nearest integer. Easy, right?

x = Math.round(x);

Sure, but is this the fastest option? I think not.

x = x < 0 ? x - 0.5 >> 0 : x + 0.5 >> 0;

What the heck's going on here? >> is JavaScript's right shift operator. It shifts a number's binary representation n bits to the right, where n is the value to the right of the operator. Since n is 0 in this case, no shifting will occur, although the resulting value will be an integer.

Note that this approach results in -82.5 being rounded to -83.

If, for some reason, your code calls Math.round() millions of times, it may be worth investigating the bitwise approach to avoid the overhead of all those function calls.

Stick to Math.round() the rest of the time, though, as it makes for much clearer code. Never optimize prematurely.

Optimization via stringification

One way to reduce the number of HTTP requests a page requires is to group (non-content) images into sprites. An even better way is to remove these images from the server altogether; instead include them as encoded strings in your style sheet.

Prototype and script.aculo.us, combined and compressed

Nothing new here. I've combined Prototype 1.6.1 and the various files that make up script.aculo.us 1.8.3 (except unittest.js) into one file, which I've minified using the YUI Compressor. Further compression has been achieved by gzipping the minified file. All three versions are available for download:

I suggest including the Prototype and script.aculo.us version numbers in the src:

<script type="text/javascript"
        src="/scripts/prototype+scriptaculous.min.js?p=1.6.1&amp;s=1.8.3"></script>

This prevents caching issues that might otherwise arise upon updating to a newer version of prototype+scriptaculous (I'll update the three files — and this post — each time a new version of Prototype is released).

Prototype loader for SyntaxHighlighter

SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript (as stated on its wiki). One of its deficiencies is that it retrieves all its brushes each time a page is loaded, despite the fact that in many cases only one or two (or none) are required.

Currently, Prototype is my JavaScript framework of choice (although I'm really looking forward to trying jQuery). I have used Prototype to create a brush loader for SyntaxHighlighter, which retrieves brushes on demand to reduce page loading times (in certain circumstances).

|| date: 27 June 2009 || time: 6:21am || || I have completely rewritten the code so that it no longer requires || empty functions inside the brush files to act as indicators of readiness. || Instead, the required brushes are retrieved in a daisy chain. This is both || more elegant and more reliable. Additionally, style sheets are now also || retrieved on demand.