let div = document.createElement('div');
div.innerHTML = '<div> hello </div>'
let div = document.createElement('div');
Object.assign(div, { innerHTML : '<div> hello </div>' })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
benchmark1 | |
benchmark2 |
Test name | Executions per second |
---|---|
benchmark1 | 216782.4 Ops/sec |
benchmark2 | 198740.0 Ops/sec |
Let's dive into the benchmark being measured on MeasureThat.net.
The benchmark compares two approaches to assigning properties to an HTML element in JavaScript: using innerHTML
property directly, and using the Object.assign()
method.
Approach 1: Using innerHTML
property
In this approach, a new <div>
element is created using document.createElement()
, and then its innerHTML
property is set directly to contain the desired HTML content. This approach is simple and straightforward but may have some performance implications due to the overhead of manipulating the DOM.
Pros:
Cons:
Object.assign()
if the element has multiple properties that need to be assigned simultaneouslyApproach 2: Using Object.assign()
method
In this approach, the same <div>
element is created as before, but instead of setting its innerHTML
property directly, the Object.assign()
method is used to assign a single object with the desired HTML content. This approach can be more efficient than the first one if multiple properties need to be assigned simultaneously.
Pros:
Cons:
Object.assign()
works (i.e., it modifies the target object in-place)Now, let's take a look at the test cases:
<div>
element using document.createElement()
, sets its innerHTML
property to contain some HTML content, and then assigns an object with more properties to the same element using Object.assign()
. The expected outcome is that the element's final state will be what was assigned in the object.Object.assign()
method directly on the <div>
element without assigning an intermediate object.In both cases, the goal is to measure which approach is faster when assigning properties to an HTML element.
The latest benchmark results show that Chrome 95 (running on a Mac OS X 10.15.7 environment) executes benchmark1 at approximately 216782 executions per second and benchmark2 at approximately 198739 executions per second. This suggests that using Object.assign()
can be faster in this specific scenario, but the difference is relatively small.
Other alternatives to these approaches include:
textContent
property instead of innerHTML
, which might be more efficient for large HTML content.Keep in mind that these alternatives might require additional setup, configuration, or understanding of the underlying libraries or frameworks.