<div id="root"></div>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
function Memo(props) {
const handler = React.useMemo(() => {
return _.debounce(props.handler, props.wait);
}, [props.handler, props.wait]);
return React.createElement("div", { className: handler() });
}
function NoMemo(props) {
const handler = _.debounce(props.handler, props.wait);
return React.createElement("div", { className: handler() });
}
var propCases = [{
handler: function() { return Math.random(); },
wait: 100
}, {
handler: function() { return Math.random(); },
wait: 200
}];
propCases.push(propCases[1]);
propCases.forEach((props, i) => {
ReactDOM.render(React.createElement(Memo, props, null), root);
});
propCases.forEach((props) => {
ReactDOM.render(React.createElement(NoMemo, props, null), root);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Memo | |
No Memo |
Test name | Executions per second |
---|---|
Memo | 14621.7 Ops/sec |
No Memo | 14417.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Definition JSON
The benchmark definition represents two different approaches to optimizing React components:
React.useMemo
to memoize a function that debounces an event handler using Lodash's _debounce
function. The memoized function is only recalculated when the dependencies (props.handler
and props.wait
) change._debounce
function on the event handler without memoizing it.Options being compared
The two options being compared are:
React.useMemo
to memoize a debounced function (Memo)React.useMemo
and instead applying debouncing directly to the event handler (No Memo)Pros and Cons of each approach
Library and purpose
The Lodash library is used in both approaches. Specifically, _debounce
is a function that takes a function as an argument and returns a new function that wraps the original function with a delay. In this case, _.debounce(props.handler, props.wait)
creates a debounced version of the event handler, which only fires after the specified wait time has passed.
Special JavaScript features or syntax
This benchmark uses the following JavaScript features:
function Memo()
and function NoMemo()
)React.useMemo
)_.debounce
)These features are widely supported in modern browsers and JavaScript environments.
Other alternatives
Other approaches to debouncing event handlers might include:
However, React Hooks and Lodash's _debounce
provide a concise and efficient way to implement debouncing in this specific use case.