Toby Smith

Posts for March 2013

Javascript Performance

20th March 2013

I’ve become quite enamored with using jsperf to benchmark the efficiency of code.

Two of the more interesting ones I’ve done (so far) are:

A comparison of various array concatination (appending one to the end of another) techniques

I look at: arr.concat, arr.push.apply(a,b), jquery’s merge and a couple of looped approaches.
The winner by a landslide:

while (b.length) {
  a.push(b.pop());
}

Even if you have to go through a few layers to access it (on the Chrome and Firefox versions I tested). Awesome!

The other was more frustrating.
A top-n sorting algorithm
Say for instance you want the top-n from an array. You’d think it might be more efficient to not have to sort the whole array and just maintaining the top few.
You’d like to think that wouldn’t you.

If you’re not using Google’s V8 engine, then you are! They seem to have uber-charged their sorting. Which is awesome. If somewhat irritating given the time wasted on custom sorting methods. 🙁
I tested it with some custom Insertion Sort and Binary Sort methods. I’m not sure a divide and conquer approach would be relevant here, but it might be worth a look.
Also worth considering the size of your n compared with the size of your arrays. I wonder if things got a bit more hairy (n = 5 ; array.length = 10,000,000) whether things would change.

http://www.thjsmith.com/feed">RSS Feed
  • Terms of use
  • Privacy Policy