Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Wednesday, March 19, 2014

It actually makes sense to implement your own sort

My mantra with algorithms is usually "somebody has probably already done it better." Why implement a sort algorithm if one already exists in your language?

With that it mind, it was a mere academic endeavor to implement Quicksort in JavaScript. I tried populating an array with a million random numbers, fully expecting Array.sort() to blow away my custom quicksort.

But guess what?

It didn't.

I ran some tests in node.js, and Array.sort() always came in last.
Array.sort() converts numbers to strings and then sorts them. For string sorting, it would probably blow away anything you could implement in JavaScript. However, for numbers, a custom sort wins.

Here are the times (in milliseconds) for sorting 1,000,000 integers

array sort (function(a,b) {return a-b;}): 518
quickSort: 235
array sort: 930

The native Array.sort() is the slowest. It returns invalid results with 999 showing up near 9996 since it is a text rather than numeric sort.

Ok, so if you are going to be sorting a huge number of integers, making your own quicksort is the way to go. But if you are looking at strings, the native sort is the way to go, right? Alas, no. For the next sample, I created 1,000,000 strings of 13 random uppercase characters and ran them through our three different scenarios. The quicksort could be used as is (the comparisons work on strings just as well.) The named sort function needed to modified slightly to handle the new sort:


function(a,b) {
if(a<b) { return -1; }
if(b<a) { return 1 };
return 0;
}


In this case, I'm just using capital letters. If there other characters involved (such as umlauts or accents), localeCompare should be used to get more appropriate results.

text sort of text array: 6625
quicksort sort of text array: 4091
named function sort of text array: 5007

Again, quicksort was the fastest, a custom function came in second, and the native sort was last. The percentage difference was not as great as with the integer sort, but the overall time difference was even greater.

The moral of this story: In most cases you will want to use your own sort function for both speed and accuracy. If you are sorting a small number of items, simply plugging a compare function into sort is probably all you need. If there are a large number of items, it would pay to implement your own sort code.

Tuesday, March 18, 2014

Data Structures and Algorithms with JavaScript

I was hoping this would be a nice advanced JavaScript programming book that would cover implementing common algorithms and data structures in JavaScript. Alas, it is instead geared towards the beginner college student. The coding examples all seem to "work" as stand alone exercises. However, they are coded in a global style that would not allow them to be extended. They use an "Easy to read" object-oriented style that flies in the face of best practices. Many also seem to reinvent the wheel. (Why create a meta-list structure that merely duplicates the pop and push operations found native on an array?)

The algorithms are also quite basic without going into great detail or even providing optimal implementations.

A much better place to look for algorithms and data structures in JavaScript is the Computer Science in JavaScript series of posts by Nick Zakas.

JavaScript Patterns

JavaScript Patterns focuses on patterns used to solve problems in JavaScript. The focus is on the language itself, with only a single chapter dedicated to browser. This is a "quality" book for advanced JavaScript programmers. It presents many of the appropriate patterns unique to doing things the "JavaScript way". It also contains a chapter on traditional object oriented design patterns in JavaScript. (These are covered in a chapter. Some are still useful in JavaScript, while others tend to be more of an academic exercise.) This book was written by somebody that knows their stuff.

High Performance JavaScript

Since this book was written in 2010, a lot has changed (and a lot has remained the same.) There are some small tweaks outlined that help gain a few microseconds here and there. Alas, many of these were already being "tweaked" out of the browser as this book was written and are now fairly irrelevant. (The applications that would benefit the most are probably not even going to be able to run in Internet Explorer 6, thus making some of these fixes totally moot.) Other bits are, however, still relevant. I'd put it more on a continuum. Some things are pretty much not worth your effort today. Others are absolutely worthwhile. And in between there are plenty of ideas that may be good in special cases.

The book includes chapters written by a number of different co-authors. Many of these authors were working at Yahoo! - back when Yahoo! was a strong innovative company. (There is still some innovation going on at Yahoo! Alas, it seems the ratio of innovation to "junk" has been decreasing.) Each author has his own style.

This book is a good candidate for a "new version" that spends some more time on algorithm enhancements, and particular areas of improvement.

Thursday, June 13, 2013

Commenting out JavaScript regular expressions in Node.js

Weird oddity commenting out code

This line works fine:


hc = hc.replace(/path=[^;]*/,"path=/"+hostMap[pref]);


However, if I try to comment out a block using /* */, things get wonky:

/*
hc = hc.replace(/path=[^;]*/,"path=/"+hostMap[pref]);
*/

The JavaScript interpreter throws a nice syntax error.
It turns out that the JavaScript interpreter sees the /* and says "cool, its a comment. I'll go until I see it close." Then it sees the */ of the regular expression and says "ok, I'm done."
It is left with some seemingly bogus line:
,"path=/"+hostMap[pref]);
*/

Now, if you could make this appear to be legitimate, you could get some seriously obfuscated code going.

The workaround is to comment out the line with the // mechanism:

//hc = hc.replace(/path=[^;]*/,"path=/"+hostMap[pref]);


Now if I could just figure out how to get chrome to start showing spell-check suggestions again...

Friday, November 09, 2012

Some JavaScript Tools

Angular.js - looks like a promising framework for javascript application development and templating. However, is still going through some early development hurdles. Today, however, I am leaning towards backbone.js, whcih seems to have some of the functionality without the overhead of a complete framework.

Raphael - a vector graphics utility. Uses SVG or VML for IE compatibility.

On top of it, you can find the ICO library of g.raphael.js

Saturday, August 13, 2011

Box2d.js

After struggle for a while, I finally creating my own box2d.js getting started page. I made some slight tweaks to the most recent standalone 2.1 version of box2d.js to allow it to run on IE 9 and IE 10. (The updated box2d.js is available there also.)

Box2d is a physics engine that is used to create games (like Angry Birds) as well as animations. The javascript version seems to hold a lot of promise, but good simple examples with the newest version were hard to come by. The examples are the result of a few days digging through google and examples to get a simple demo fully rendered in a single canvas.