When dealing with huge arrays, and you want to filter elements out of the array, in terms of performance, is it better to create a new array and just push the ones you want to keep in that new array, or manually remove elements from the existing array using something like this Deleting array elements in JavaScript - delete vs splice
Does anyone know?
Thanks
creating a new array and pushing consume more time and also memory. But deleting will not take much time and free memory.
If you create a new array and push, it has to compare each and every element and then push.
If you delete, it has to only compare and delete.
Second option is good for performance
You can use splice() to delete an item from the array. consider the below example, if you want to delete the item 3 of index of 2 you can use splice(position,range)
var a = [1,2,3,4,5,6,7];
a.splice(2,1);
console.log(a);
This will output
[1, 2, 4, 5, 6, 7]
The answer should be able to be determined definitively, without speculation, by running the tests using different array methods, or other approaches.
var arr = Array(7); var r = 3; console.time(".splice()"); arr.splice(r, 1); // try different methods here console.timeEnd(".splice()"); var arr = Array(7); console.time(".filter()"); arr = arr.filter(function(_, i) { // try different methods here return i !== r }); console.timeEnd(".filter()");
var arr = Array(1000); var r = 500; console.time(".splice()"); arr.splice(r, 1); console.timeEnd(".splice()"); var arr = Array(1000); console.time(".filter()"); arr = arr.filter(function(_, i) { return i !== r }); console.timeEnd(".filter()");
var arr = Array(100000); var r = 50000; console.time(".splice()"); arr.splice(r, 1); console.timeEnd(".splice()"); var arr = Array(100000); console.time(".filter()"); arr = arr.filter(function(_, i) { return i !== r }); console.timeEnd(".filter()");
You can use splice method to modify the content of array. If you want to add an element use -
arrayName.splice(index,range,element);
If you want to remove an element use -
arrayName.splice(index,deleteCount);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.