<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute("class", "bar");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute("class", "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
SetAttribute Single | |
SetAttribute Multi |
Test name | Executions per second |
---|---|
SetAttribute Single | 15318.3 Ops/sec |
SetAttribute Multi | 8730.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition and Preparation Code
The benchmark definition is a JSON object that describes the test to be performed. In this case, there are two benchmarks:
SetAttribute Single
: This benchmark tests setting a single attribute on an HTML element.SetAttribute Multi
: This benchmark tests setting multiple attributes on an HTML element.The preparation code is empty for both benchmarks, which means that MeasureThat.net will generate the necessary HTML and JavaScript context automatically.
Individual Test Cases
Each test case consists of two parts:
Benchmark Definition
: This is a string representing the actual JavaScript code that defines the benchmark. In this case, there are two benchmark definitions:SetAttribute Single
: Sets a single attribute "class" on an HTML element with id "foo".SetAttribute Multi
: Sets multiple attributes on an HTML element with id "foo", each with a different value.Test Name
: This is a human-readable name for the test case.Options Compared
In both benchmark definitions, the same approach is used to set the attribute(s) on the HTML element:
document.getElementById
method to retrieve the element by its id.setAttribute
method.The only difference between the two test cases is the number of attributes being set.
Pros and Cons
Using this approach has both pros and cons:
Pros:
Cons:
Library Used
In this case, no explicit library is mentioned. However, the use of document.getElementById
implies that MeasureThat.net is using the DOM (Document Object Model) API, which is a built-in part of most web browsers.
Special JS Feature or Syntax
There are no special JavaScript features or syntax used in these benchmark definitions. The code is simple and follows standard JavaScript conventions.
Other Alternatives
If you were to rewrite this benchmark using alternative approaches, here are some options:
document.getElementById
method, you could use a library like Lodash to access the element by its id.Keep in mind that these alternatives would require significant changes to the benchmark definition and code, and might not be suitable for all use cases.