Я провел небольшой тест и обнаружил, что array.sort(function(a, b) { return a - b; });
намного быстрее, чем array.sort();
в JavaScript.
Результаты были довольно шокирующими, примерно в 1,7 раза быстрее в IE9, в 1,6 раза в FF7 и в 6,7 раза в Chrome.
Кроме того, реализовав саму быструю сортировку в JS, я обнаружил, что это даже быстрее, чем оба метода, упомянутых выше.
(Две разные реализации, одна принимает функцию сравнения в качестве параметра, другая - нет. Обе были быстрее.)
Есть ли разумное объяснение?
РЕДАКТИРОВАТЬ: Мои реализации:
Нет сравнения:
function quickSort(array, from, to) {
if(typeof from === 'undefined') {
from = 0;
to = array.length - 1;
}
else if(typeof to === 'undefined') {
to = array.length - 1;
}
if(to - from < 1) {
return;
}
var i = from, pivot = to, t;
while(i < pivot) {
if(array[i] > array[pivot]) {
t = array[i];
array[i] = array[pivot - 1];
array[pivot - 1] = array[pivot];
array[pivot] = t;
pivot--;
}
else {
i++;
}
}
quickSort(array, from, pivot - 1);
quickSort(array, pivot + 1, to);
}
С компаратором:
function quickSortFunc(array, sortfunc, from, to) {
if(typeof from === 'undefined') {
from = 0;
to = array.length - 1;
}
else if(typeof to === 'undefined') {
to = array.length - 1;
}
if(to - from < 1) {
return;
}
var i = from, pivot = to, t;
while(i < pivot) {
if(sortfunc(array[i], array[pivot]) > 0) {
t = array[i];
array[i] = array[pivot - 1];
array[pivot - 1] = array[pivot];
array[pivot] = t;
pivot--;
}
else {
i++;
}
}
quickSortFunc(array, sortfunc, from, pivot - 1);
quickSortFunc(array, sortfunc, pivot + 1, to);
}