J'ai fait un petit test, et j'ai découvert que array.sort(function(a, b) { return a - b; });
est beaucoup plus rapide que array.sort();
en JavaScript. Les résultats ont été assez choquants, environ 1,7 fois plus rapide dans IE9, 1,6 fois dans FF7 et 6,7 fois dans Chrome.JavaScript, le tri avec le second paramètre est plus rapide
De plus, en implémentant quicksort par moi-même dans JS, j'ai trouvé que c'était encore plus rapide que les deux méthodes mentionnées ci-dessus. (Deux implémentations différentes, l'une accepte une fonction de comparaison en tant que paramètre, l'autre non, les deux étaient plus rapides.)
Y a-t-il une explication raisonnable?
EDIT: Mes implémentations:
Non comparateur:
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);
}
Avec comparateur:
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);
}
Il est possible que la fonction de tri est exécuté à partir des moyennes. Quelle était la taille des tableaux que vous avez utilisés? – Matt
Le tri "Normal" fonctionne sur la représentation sous forme de chaîne des éléments. Cela pourrait être un surcoût possible. –
Matt, je l'ai testé sur des tableaux de 100, 1000, 10000 et 100000 éléments. Félix, je pense à ce sujet, cela n'explique toujours pas pourquoi mon implémentation avec un comparateur est plus rapide que l'implémentation native avec un comparateur. –