<table id="testTable">
</table>
// some elemens without id
for(var i=0; i<5000; ++i)
testTable.insertRow(-1).insertCell(-1).textContent = 'Row #'+i;
// some elements with id
var parent = testTable.parentElement;
for(var i=0; i<5000; ++i)
{
var div = document.createElement('div');
div.id = 'divBefore'+i;
parent.insertBefore(div, testTable);
div = document.createElement('div');
div.id = 'divAfter'+i;
parent.appendChild(div);
}
for(var i=0; i<10000; ++i)
{
var table = document.getElementById('testTable');
table.rows[0].cells[0].textContent = 'Test';
}
var table = document.getElementById('testTable');
for(var i=0; i<10000; ++i)
{
table.rows[0].cells[0].textContent = 'Test';
}
var testTable = document.getElementById('testTable');
for(var i=0; i<10000; ++i)
{
testTable.rows[0].cells[0].textContent = 'Test';
}
for(var i=0; i<10000; ++i)
{
testTable.rows[0].cells[0].textContent = 'Test';
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById each time | |
Own global variable | |
Own global variable with equal name | |
HTML5 global variable based on id value |
Test name | Executions per second |
---|---|
getElementById each time | 175.3 Ops/sec |
Own global variable | 363.3 Ops/sec |
Own global variable with equal name | 347.1 Ops/sec |
HTML5 global variable based on id value | 86.3 Ops/sec |
Let's dive into the benchmark analysis.
Benchmark Definition JSON
The provided JSON represents a benchmark that compares four different approaches to accessing an HTML element by its ID:
getElementById
each time: Accessing the element using the document.getElementById()
method repeatedly.getElementById
call, effectively reusing the cached result.window.
namespace with the ID as a property.Options Compared
The benchmark compares the performance of these four approaches to accessing an HTML element by its ID:
document.getElementById()
getElementById
call, effectively reusing the cached resultPros and Cons
getElementById
each time: This is the most straightforward approach, but it incurs repeated DOM queries, which can be slower and more resource-intensive.window.
) to access the element, making it faster since there's no repeated query overhead.Library
In this benchmark, the library is not explicitly mentioned. However, the usage of document
and the DOM methods like getElementById
, insertRow
, and appendChild
suggests that the test relies on the browser's native API for manipulating HTML elements.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes used in this benchmark beyond the standard language. The focus is solely on comparing different approaches to accessing an element by its ID.
Alternatives
Other alternatives to these approaches could include:
$('#testTable')
).Keep in mind that this benchmark is designed to compare specific approaches to accessing an element by its ID, so these alternatives might not be relevant to the actual use case.