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.