I observed a lower performance of the .sort()
implementation for typed integer arrays compared to untyped arrays on current JavaScript engines.
My intuition tells me that TypedArray.prototype.sort()
should be faster since it performs a numeric comparison by default rather than the string comparison used by Array.prototype.sort()
for which we would thus need to supply a compare function (a, b) => b - a
.
In practice however, this intuition is wrong. Chrome and Firefox both sort the untyped array (much) faster:
var length = 1000,
array = new Array(length),
int32Array = new Int32Array(length);
// Fill arrays with random integers:
for (var i = 0; i < length; ++i) {
int32Array[i] = array[i] = Math.random() * length | 0;
}
// Run benchmark.js test suite:
var suite = new Benchmark.Suite;
suite.add('Array.sort', function() {
var input = array.slice();
var result = input.sort((a, b) => b - a);
})
.add('Int32Array.sort', function() {
var input = int32Array.slice();
var result = input.sort();
})
.on('complete', function() {
console.log(this[0].toString());
console.log(this[1].toString());
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run();
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.0/benchmark.js"></script>
The difference must be caused by .sort
and not .slice
which runs about two orders of magnitude faster than the former.
Is there an inherent reason explaining the observed low performance?
PS: According to Fastest way to sort 32bit signed integer arrays in JavaScript?, the fastest way to sort an integer array is to supply one's own .sort
implementation.
2017 Update: On Firefox 52 / Ubuntu, sorting Int32Array now performs slightly faster than for the untyped array.