Eu tenho uma mesa enorme (até 10 000 linhas). Eu tenho que passar por todas as linhas, calcular alguns dados e escrevê-los em duas células em cada linha.
Eu faço algo parecido com:
$("#table tbody").find("tr:visible").each(function() {
var tr = $(this);
var a = tr.children(".cell3").text();
tr.children(".cell4").html(xxx.calculate(parseFloat(tr.children(".cell1").text()), a, b ));
tr.children(".cell5").html(xxx.calculate(parseFloat(tr.children(".cell2").text()), a, b));
});
e vejo, perfilando, é aqui que a maior parte do tempo é gasta durante o cálculo.
Tentei armazenar em cache todos os filhos (var tds tr.children (". Cell1, .cell2, .cell3")) e use tds.get () para recuperar valores.
Eu tentei usar o método nativo innerHTML js
Mas não tive melhorias significativas.
Você tem algum conselho ou vê algo ruim no meu código? É o melhor que posso obter?
PS: As células podem estar em uma ordem diferente, então eu tenho que acessá-las através do nome da classe
Respostas:
0 para resposta № 1São 10000 linhas a percorrer, para obter algum ganho, tente usar o método nativo o máximo possível.
Algumas sugestões rápidas, não sei se resultará em grande ganho, mas deve ser relativamente rápido:
1. Use simples para loop, com comprimento em cache
10000 linhas para loop são o melhor caso de teste para verificar a diferença de desempenho entre $ .each e plain para loop.
var items = $("#table tbody").find("tr:visible");
var length = items.length;
for(var i = 0; i< length; i++)
{
var tr = $(items[i]);
var a = tr.children(".cell3").text();
tr.children(".cell4").html(xxx.calculate(parseFloat(tr.children(".cell1").text()), a, b ));
tr.children(".cell5").html(xxx.calculate(parseFloat(tr.children(".cell2").text()), a, b));
}
2. Use find () em vez de children (), marque jsperf aqui
var items = $("#table tbody").find("tr:visible");
var length = items.length;
for(var i = 0; i< length; i++)
{
var tr = $(items[i]);
var a = tr.find(".cell3").text();
tr.find(".cell4").html(xxx.calculate(parseFloat(tr.find(".cell1").text()), a, b ));
tr.find(".cell5").html(xxx.calculate(parseFloat(tr.find(".cell2").text()), a, b));
}