During my recent studies for the new data binding layer I implemented an array wrapper in qooxdoo. The best way for a reduced set of API changes compared to the native array was to map the native JavaScript array to a qooxdoo array and add some custom events to the qooxdoo implementation. Doing that, I discovered some strange behavior of the browsers' implementation of the sort() method for a native JavaScript array.

The following code demonstrates this:

 
<html>
<head>
	<script type="text/javascript">
 
function load() {
  var array = [1, 2, 3];
  array.sort(function(a, b) {
    document.getElementById("out").innerHTML +="a: " + a + ", b: " + b + "<br/>";
    return a > b;
  });
}
	</script>
</head>
<body onload="load()">
<div id="out"/>
</body>
</html>
 

The important part is the sort() method, which is given a function to sort the JavaScript Array. This function logs the given parameters to the innerHTML of an DIV element. The results for the array [1, 2, 3] were more different between browsers than I thought:

Output: FF3
a: 1, b: 2
a: 2, b: 3

Output: Safari 3.2
a: 1, b: 2
a: 2, b: 3

Output: Opera 9.6
a: 2, b: 1
a: 3, b: 1
a: 3, b: 2

Output: IE 7
a: 2, b: 3
a: 3, b: 1
a: 2, b: 3

As you can see, there is no difference between Firefox 3 and Safari 3 (and never were during all my tests), but there are some remarkable differences to Opera and Internet Explorer. By returning always '-1' as a result of the sort function, I created the best case for those two sort algorithms, while creating rather a worst case for the others. Another interesting part is, that the order of the parameters is different among algorithms.

As a consequence you might not have a roughly equivalent execution time in all browsers, even with the same sort function And you can not rely on the order of the parameters, even if the array is already sorted before the actual call of the sort function.

Try out the corresponding test application yourself.