<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
<div id="root"></div>
<script type="text/jsx">
class AppComp extends React.Component {
constructor() {
super();
this.state = {
count : 0,
type : 'fn'
}
}
render() {
return (
<div>
{this.state.type === 'fn' ?
<DisplayAsFn value={this.state.count} />
:
<DisplayAsVar value={this.state.count} />
}
</div>
);
}
}
function DisplayAsFn({value}) {
const renderValue = () => {
return <span>{value}</span>
};
return <div>Fn : {renderValue()}</div>
}
function DisplayAsVar({value}) {
const renderValue = <span>{value}</span>
return <div>Var : {renderValue}</div>
}
var appComp = ReactDOM.render(
<AppComp />,
document.querySelector('#root')
);
function add1() {
appComp.setState({count: appComp.state.count + 1});
}
function setType(type) {
appComp.setState({type});
}
</script>
appComp.setState({
count: appComp.state.count + 1,
type : 'fn'
});
appComp.setState({
count: appComp.state.count + 1,
type : 'var'
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Render with Fn | |
Render with Var |
Test name | Executions per second |
---|---|
Render with Fn | 339941.1 Ops/sec |
Render with Var | 342274.9 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares the performance of two approaches to rendering rules in a React application:
DisplayAsVar
function.DisplayAsFn
function.Options Compared
The benchmark is testing two options:
var
) to store the render rule.fn
) to store the render rule.Pros and Cons of Each Approach
Library: JSXTransformer
The benchmark uses the JSXTransformer
library to enable JSX syntax support. JSX is a syntax extension that allows developers to write HTML-like code in their JavaScript files. The JSXTransformer
library is responsible for transforming this syntax into standard JavaScript code that can be executed by the browser.
Special JS Feature: Closures
The benchmark uses anonymous functions (closures) to store and apply render rules. A closure is a function that has access to its own scope, including variables from its outer function. In this case, the DisplayAsFn
and DisplayAsVar
functions create closures over the value
parameter, which allows them to modify the render rule based on the value of state.count
.
Other Alternatives
If you're interested in exploring other alternatives for rendering rules or optimizing performance in React applications, here are a few options:
React.createRef()
: Instead of defining variables or anonymous functions to store render rules, consider using React.createRef()
to create references that can be used to update the DOM.render
method.I hope this explanation helps! Let me know if you have any further questions.