Performance optimization

2 snippets across 2 stacks - React, Regular Expressions

REReact

When to Memoize

RE · useMemo & useCallback
Syntax
// DO memoize when:
// - Computation is genuinely expensive (sorting large arrays, complex math)
// - Passing callbacks/objects to React.memo children
// - Value is a dependency of another hook

// DON'T memoize when:
// - The computation is trivial
// - The component rarely re-renders
// - No downstream consumer cares about reference stability
Example
// GOOD: expensive computation
const sortedTransactions = useMemo(
  () => transactions.slice().sort(compareDates),
  [transactions]
);

// GOOD: stable reference for memoized child
const handleDelete = useCallback(
  (id) => dispatch({ type: 'DELETE', id }),
  [dispatch]
);

// UNNECESSARY: trivial computation
// const label = useMemo(() => `Hello ${name}`, [name]);
// Just write: const label = `Hello ${name}`;

Note Memoization has a cost: it uses memory to store results and adds comparison overhead. Only apply it where profiling shows a measurable benefit. Premature memoization adds complexity without improving performance.

RXRegular Expressions

Possessive Quantifiers (Concept)

RX · Quantifiers
Syntax
*+  ++  ?+  {n,m}+   (not supported in JS or Python re)
Example
Java/PCRE:  '"hello"'.match(/"[^"]*+"/)
Python alternative: use atomic group via regex module
  import regex
  regex.search(r'"(?>"[^"]*)"+', text)
Output
Matches "hello" without backtracking into the quoted content

Note Possessive quantifiers never give back characters once matched. They prevent catastrophic backtracking but cause a match to fail if the rest of the pattern cannot match. Not available in JavaScript or Python's built-in re module -- use the third-party 'regex' module in Python or atomic groups in PCRE.

Frequently asked questions

How does React handle performance optimization?
This task is covered in 2 stacks on this page: React, Regular Expressions. The "When to Memoize" snippet in React uses `// DO memoize when:`.
Which code does the React example use?
The "When to Memoize" snippet uses `// DO memoize when:`, from the useMemo & useCallback section of the React cheat sheet.
Which stacks cover "performance optimization" on this page?
React, Regular Expressions. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "When to Memoize": Memoization has a cost: it uses memory to store results and adds comparison overhead. Only apply it where profiling shows a measurable benefit. Premature memoization adds complexity without improving performance.