Practical software engineering foundations · Lesson 59 of 60 · Concept lesson · Optional
Performance optimization
Performance work starts with measuring, because the slow part is often not where you expect.
Profiling finds where time is spent, and caching saves the result of slow work so you can reuse it.
Only optimize what the measurements show matters, because faster code is often harder to read.
Picture it
Code example
const cache = {};
function fib(n) {
if (n < 2) return n;
if (cache[n] !== undefined) return cache[n];
cache[n] = fib(n - 1) + fib(n - 2);
return cache[n];
}
console.log(fib(40));Output: 102334155
Without the cache this would make hundreds of millions of calls. With it, each value is worked out once.
cache = {}
def fib(n):
if n < 2:
return n
if n not in cache:
cache[n] = fib(n - 1) + fib(n - 2)
return cache[n]
print(fib(40))Output: 102334155
Without the cache this would make hundreds of millions of calls. With it, each value is worked out once.
Check yourself
Pick an answer for each question. You can retry as many times as you like.
Loading the questions…