Cache frequently accessed or computed values to avoid redundant calculations and property lookups. This applies to: 1. Loop invariant values 2. Expensive computations
Cache frequently accessed or computed values to avoid redundant calculations and property lookups. This applies to:
Example - Before:
while (index < path.length) {
// path.length accessed on every iteration
if (path.indexOf(separator, index) !== -1) {
// indexOf called multiple times
}
}
Example - After:
const pathLength = path.length; // Cache loop invariant
const separatorIndex = path.indexOf(separator, index); // Cache computation
while (index < pathLength) {
if (separatorIndex !== -1) {
// Use cached values
}
}
This optimization is particularly important in performance-critical paths and loops. When implementing, consider:
The performance impact can be significant, especially when the cached values are used frequently or the computations are expensive.
Enter the URL of a public GitHub repository