我有一個pendingOrders數組,我需要在循環中檢查Order狀態的邏輯。從數組中刪除項目或爲剩餘項目(Javascript)創建新數組是有效的
我想知道從原始數組中刪除已完成的項目是否有效,或者爲剩餘訂單創建新數組是否有效。
這可能不是很大的節省,但仍然很高興理解這一點。
var pendingOrders = [ ];
pendingOrders[0] = {OrderId: 1};
pendingOrders[1] = {OrderId: 2};
pendingOrders[2] = {OrderId: 3};
//Call CheckOrderStatus function
CheckOrderStatus(pendingOrders);
CheckOrderStatus(pendingOrders)
{
//Some logic to find completed orders
//Suppose OrderId : 1 is completed
//Now which one of following will be efficient ?
//Approach 1 - remove Completed Orders from original array pendingOrders using function removeByAttribute (given below)
//Remove object by value
removeByAttribute (pendingOrders, 'OrderId', 1);
//again call this after 10 seconds
CheckOrderStatus(pendingOrders);
//OR
//Approach 2 - instead of removing simply create new array
//Simply create new array for remaining orders
var stillPendingOrders = [ ];
stillPendingOrders [1] = {OrderId: 2};
stillPendingOrders [2] = {OrderId: 3};
//again call this after 10 seconds
CheckOrderStatus(stillPendingOrders);
}
/*Utility Function: Removes an Object Item from an array -
*
* @param arr - Array
* @param attr - Attribute name
* @param value - Attribute value
*
* @returns arr - modified array
*/
var removeByAttribute = function(arr, attr, value){
var i = arr.length;
while(i--){
if(arr[i] && arr[i].hasOwnProperty(attr) && (arguments.length > 2 && arr[i][attr] === value)){
arr.splice(i,1);
}
}
return arr;
}
幾乎所有JavaScript性能問題的答案都是***取決於***。有些東西在某些引擎上效率更高,而其他引擎效率更低。要知道的唯一方法是在目標引擎上測試它(使用http://jsperf.com或類似的)。另外,「高效」是一個模糊的術語 - 在某種意義上是有效的?速度?內存消耗/內存流失? – 2014-09-25 08:39:07
我主要關心速度問題,而關於內存消耗的問題卻很少? – Maverick09 2014-09-25 08:59:40