<div id="root"><div>
var el = document.getElementById("root");
function getStyle(elem){
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
}
function getStyle2(elem){
return window.getComputedStyle( elem );
}
var computedStyle = getStyle(el);
var computedStyle = getStyle2(el);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ownerDocument.defaultView | |
window.getComputedStyle |
Test name | Executions per second |
---|---|
ownerDocument.defaultView | 732782.1 Ops/sec |
window.getComputedStyle | 1064090.8 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Definition
The benchmark defines two different approaches to retrieve the computed style of an HTML element:
ownerDocument.defaultView
: This approach uses the ownerDocument
property to access the default view, which is the top-level window object associated with a document. It then uses the getComputedStyle()
method of this view to retrieve the computed style.window.getComputedStyle
: This approach directly uses the window.getComputedStyle()
method to retrieve the computed style.Options Compared
The two options are being compared in terms of performance, specifically:
ownerDocument.defaultView
: This option may provide an advantage in certain cases where the window object is not available or is not associated with a valid document. However, it's unclear whether this will be relevant for most use cases.window.getComputedStyle
: This is a widely used and well-established method for retrieving computed styles.Pros and Cons
ownerDocument.defaultView
:window.getComputedStyle
:Library/Functionality
The benchmark uses two JavaScript functions:
getStyle()
: This function is defined in the "Script Preparation Code" section of the benchmark definition. It returns the computed style of an element using either ownerDocument.defaultView
or window.getComputedStyle
, depending on whether a valid window object is available.getStyle2()
: This function is also defined in the "Script Preparation Code" section and simply calls window.getComputedStyle()
to retrieve the computed style.Special JS Feature/Syntax
There are no special JavaScript features or syntax used in this benchmark, only standard ES5 JavaScript.
Other Alternatives
Alternative approaches could include:
css-dom
to provide a standardized API for accessing computed styles.Keep in mind that these alternatives would likely introduce additional complexity and potential overhead compared to the simple window.getComputedStyle
approach used in this benchmark.