<div id="test"></div>
window.el = document.getElementById("test");
let i = 0;
const styleObject = el.style;
while (i < 10000) {
styleObject.setProperty("left","100px");
styleObject.setProperty("top","100px");
i++;
}
let i = 0;
while (i < 10000) {
el.setAttribute('style',"left: 100px; width: 100px; height: 50px; top: 100px;border-radius: 0;border-width: 0;background: 0 0;font-family: inherit;font-size: inherit;margin: 0;white-space: pre;word-wrap: normal;line-height: inherit;color: inherit;z-index: 2;position: relative;overflow: visible;-webkit-tap-highlight-color: transparent;");
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
style.setProperty | |
setAttribute |
Test name | Executions per second |
---|---|
style.setProperty | 192.7 Ops/sec |
setAttribute | 232.5 Ops/sec |
Let's break down the provided benchmark and its test cases.
What is being tested?
The benchmark is testing two different ways to set CSS styles on an HTML element:
setAttribute
: Setting the style
attribute of an element using the setAttribute()
method.setProperty
: Setting a specific CSS property of an element using the setProperty()
method.Options compared:
setAttribute
vs setProperty
setAttribute
is used to set the entire style
attribute, which can contain multiple properties (e.g., width
, height
, etc.). It's often faster because it doesn't require parsing or compiling the individual properties.setProperty
is used to set a specific CSS property, like left
or top
. It's typically slower because it requires more overhead for parsing and compiling the individual property.Pros and Cons of each approach:
setAttribute
:style
attributesetProperty
:Library/Features:
el
is an alias for the HTML element with the ID "test", which is a DOM element.window.el = document.getElementById("test");
: This line of code creates an alias for the DOM element, making it easier to reference in the benchmark.Special JS feature/syntax:
None mentioned in this specific benchmark. However, keep in mind that some JavaScript features or syntax might affect performance in general, such as:
const
and let
declarationsAlternatives:
Other methods for setting CSS styles include:
style
attribute directly (e.g., el.style.left = "100px"
): This approach is similar to setAttribute
, but it's more concise and might be faster.Keep in mind that the choice of method depends on your specific use case, project requirements, and personal preference. The benchmark provided by MeasureThat.net aims to help developers understand the relative performance of different approaches to setting CSS styles in JavaScript.