Skip to content

Instantly share code, notes, and snippets.

@finscn
Created January 14, 2013 10:29
Show Gist options
  • Save finscn/4529159 to your computer and use it in GitHub Desktop.
Save finscn/4529159 to your computer and use it in GitHub Desktop.
array splice vs non-splice
function createObjectArray(length){
var arr=[];
for (var i=0;i<length;i++){
var obj={
id : "id_"+i,
foo : "bar",
value : i
};
arr.push(obj);
}
return arr;
}
function sortObjectArray(arr){
arr.sort(function(a,b){
return a.value-b.value;
});
}
function useSwap(len){
var move=len>>1;
var arr=createObjectArray(len);
console.time("useSwap");
for (var i=0;i<move;i++){
arr[len>>1]=arr[len-1]
len--;
}
arr.length=len;
// sortObjectArray(arr);
console.timeEnd("useSwap");
}
function useSplice(len){
var move=len>>1;
var arr=createObjectArray(len);
console.time("useSplice");
for (var i=0;i<move;i++){
arr.splice(len>>1,1);
len--;
}
// sortObjectArray(arr);
console.timeEnd("useSplice");
}
var arrayLength=2000;
useSwap(arrayLength);
useSplice(arrayLength);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment