Come ci comporta jQuery quando deve gestire grandi strutture di dati? Vediamolo insieme.
Il seguente codice PHP crea una tabella con 30000 righe e 90000 celle:
<?php
$total = 30000;
?>
<table>
<tr>
<th scope="col">A</th>
<th scope="col">B</th>
<th scope="col">C</th>
</tr>
<?php
for($i = 0; $i < $total; $i++) {
echo '<tr>' . "\n";
echo '<td>' . ($i + 1) . '</td>' . "\n";
echo '<td>' . ($i + 1) . '</td>' . "\n";
echo '<td>' . ($i + 1) . '</td>' . "\n";
echo '</tr>' . "\n";
}
?>
</table>
Per prima cosa testiamo il selector engine su questa tabella:
$('td:nth-child(even)', 'table').text('0'); // funziona (Chrome)
Il secondo test riguarda i loop e la manipolazione del DOM:
$('td', 'table').each(function(i) {
var $td = $(this);
var n = Number($td.text());
$td.text(n + i);
});
In Chrome viene restituito un errore, ma il browser non va in crash:
Uncaught RangeError: Maximum call stack size exceeded
Se invece usiamo l'approccio DOM, il browser va in crash:
var td = document.getElementsByTagName('td'),
len = td.length,
i;
for( i = 0; i < len; ++i) {
var cell = td[i];
var text = cell.firstChild.nodeValue;
var n = Number(text);
var sum = n + 1;
cell.innerHTML = sum;
}
Il file HTML generato da PHP pesa 1.7 Mb. Sebbene sia uno scenario improbabile, tuttavia questo test rivela i limiti di jQuery con le grandi strutture di dati.