如何拆分通过巨大数组循环的过程?

问题描述 投票:0回答:1

我有一个包含1000个复杂对象的数组。

我需要遍历数组以运行某些功能,当数组很小(如100个产品)时,性能似乎还不错。

但是当达到400种或以上的产品时,在浏览器上的性能将大大下降。

所以我想先循环浏览前100种产品,然后再继续循环接下来的100种产品。

不确定这是个好主意吗?有没有更好的方法来处理遍历庞大数组的循环?


代码示例

实际情况是遍历选定的1000个复选框。

我具有将li动态附加到DOM的功能。

populateEnrichedProductList = (id, name) => {
        let html =
                `<li class="list-group-item product-item-name" productName="${name}" productId="${id}" data-desc="" data-ingredient="" data-allergens="">` +
                `${name}` +
                `<span class="error"><i class="fas fa-exclamation-triangle"></i></span>` +
                '<div class="spinner">' +
                '<div class="spinner-border text-warning" role="status">' +
                '<span class="sr-only">Loading...</span>' +
                '</div >' +
                '</div>' +
                '</li >';

                $('#selectedProductList').removeClass('hidden');    
                $('#productListUL').addClass('hidden');
                $('#selectedProductList').append(html);
    };

这里,我遍历选中的项,然后为数组的每个项运行函数populateEnrichedProductList

let selectedProducts = '#selectProductForm input:checked';
$(selectedProducts).each(function(){
            let pid   = $(this).attr('id'),
                pname = $(this).attr('name');

            populateEnrichedProductList(pid, pname);
        });

如前所述,当数组很小时没有问题,但是当数组中有更多数据时性能会下降。

如果有人可以展示一个更好地处理它以提高性能的示例,那就太好了。

javascript jquery arrays loops iteration
1个回答
0
投票

您可以将阵列拆分为多个部分。看这段代码。这是对数组元素进行加密的示例,但是您可以在逻辑中使用此模式。

const crypto = require('crypto')

const arr = new Array(200).fill('something')
function processChunk() {
  if (arr.length === 0) {
    // code executed after processing the entire array
  } else {
    console.log('processing chunk');
    // select 10 elements and remove them from the array
    const subarr = arr.splice(0, 10)
    for (const item of subarr) {
    // perform complex processing of each of the elements
      doHeavyStuff(item)
    }
    // put the function in the queue
    setImmediate(processChunk)
  }
}

processChunk()

function doHeavyStuff(item) {
  crypto.createHmac('sha256', 'secret').update(new Array(10000).fill(item).join('.')).digest('hex')
}

// This fragment is needed only to confirm that, processing a large array,
// We give the opportunity to execute another code.

let interval = setInterval(() => {
  console.log('tick!')
  if (arr.length === 0) clearInterval(interval)
}, 0)
© www.soinside.com 2019 - 2024. All rights reserved.