<textbox id="text"></textbox>
var element = document.getElementById("text");
var i = 10000;
while (i--) {
element.setAttribute("value", i);
}
var element = document.getElementById("text");
var i = 10000;
while (i--) {
element.value = i;
}
var element = document.getElementById("text");
var i = 10000;
while (i--) {
element["value"] = i;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
setAttribute | |
direct | |
[] |
Test name | Executions per second |
---|---|
setAttribute | 562.4 Ops/sec |
direct | 287973.0 Ops/sec |
[] | 289110.4 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Purpose: The benchmark measures the performance of three different approaches to setting the value of an HTML input element:
setAttribute
element.value = i
)element["value"] = i
)Options Comparison:
setAttribute
: This method uses the setAttribute
method to set the value attribute of the input element. It takes two arguments: the attribute name and the value.value
property of the input element.value
property of the input element using square brackets ([]
). The syntax is element["value"] = i
.Pros and Cons:
setAttribute
:Library and Syntax: None of the options require any external libraries or special JavaScript features. They are all basic syntax for working with HTML elements in JavaScript.
Other Considerations:
value
property is a setter function that calls the setAttribute
method internally. This means that direct assignment (element.value = i
) may be equivalent to setAttribute
in terms of performance.element["value"] = i
) can be slower due to the overhead of resolving the bracket notation.Benchmark Results: The benchmark results show that:
element.value = i
) is the fastest approach, followed closely by property access with square brackets (element["value"] = i
).setAttribute
is the slowest approach.Keep in mind that these results may vary depending on the specific browser, version, and hardware configuration.