Performance and Load Testing Basics
Build a working model of automated testing from assertions to unit, component, API, integration, contract and end-to-end tests, then apply it to a single progressive task-board capstone where each milestone adds a real defect, a failing test, a corrected implementation and an expected result.
What you will be able to do
#- Distinguish a performance assertion from a functional assertion.
- Write a stable timing test with a generous budget.
- Describe what a load test measures and where it runs.
Overview
#Performance is a behavior
A function that is correct but takes ten seconds is a defect for the user. Performance tests assert on time, memory or throughput rather than on returned values. They are tests, so they need the same determinism discipline as any other test.
Timing tests are inherently noisy
Wall-clock time depends on the machine, the load and the garbage collector. A test that asserts a function runs in under 5 milliseconds will fail on a busy CI runner. Two techniques help. First, use a generous budget: assert under 200 milliseconds for something that should take 2, which catches a catastrophic regression without flaking. Second, assert on relative behavior: a memoized call must be faster than the first call, or an O(n) function must scale better than an O(n squared) one across two input sizes.
const start = Date.now();
run();
const elapsed = Date.now() - start;
if (elapsed > 200) throw new Error('too slow: ' + elapsed + 'ms');
Measure before you assert
Do not guess a budget. Measure the current behavior, then set the assertion well above it, so the test catches a real regression rather than normal variation. A budget that is too tight is a flaky test; one that is too loose catches nothing.
Complexity assertions
A robust way to test performance is to assert on growth, not absolute time. Run the function at size n and size 2n. A linear function roughly doubles; a quadratic function roughly quadruples. Assert the ratio stays below a threshold that separates the two. This is far more stable than absolute timing.
Load testing measures a system
A load test drives many concurrent requests against a running system and measures latency percentiles and error rate. It needs a real running server and real network, so it runs in a dedicated environment, not in a unit test or a browser sandbox. Report the p95 and p99 latency, not just the average, because averages hide the slow requests users notice.
Keep performance tests out of the fast path
Performance tests are slower and noisier than unit tests. Run them on a schedule or before release, not on every save. Keep them separate so a noisy timing failure does not block unrelated work.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
A linear function takes about 10ms at size 1000. Roughly what does it take at size 2000?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascript// linear: time is proportional to input sizeExercise 2Explain
Explain why asserting a growth ratio is more stable than asserting an absolute time.
Reveal the reference answer
reference.javascriptAbsolute time depends on the machine, background load and the garbage collector, so a fixed millisecond budget flakes. A growth ratio compares the function to itself at two input sizes on the same machine in the same run, so machine speed largely cancels out. A linear function roughly doubles and a quadratic roughly quadruples, and the ratio separates them reliably even on a slow runner.The answer should explain that the ratio cancels machine-specific factors, making the assertion portable and stable.
Exercise 3Implement
Implement `growthRatio(fn, n)` that returns the time at size 2n divided by the time at size n, using Date.now(). `console.log(typeof growthRatio((k) => { let s = 0; for (let i = 0; i < k; i++) s += i; return s; }, 1000))` should print `number`.
starter.javascriptfunction growthRatio(fn, n) { // your code here }Reveal the reference answer
reference.javascriptfunction growthRatio(fn, n) { const t1 = Date.now(); fn(n); const small = Math.max(Date.now() - t1, 1); const t2 = Date.now(); fn(2 * n); const large = Date.now() - t2; return large / small; }Authored expected output: number
The helper times the function at n and 2n and returns the ratio. The Math.max guard prevents division by zero when the small run is faster than the clock resolution.
Exercise 4Debug
This performance test is flaky because the budget is too tight. Raise the budget so it catches only a real regression.
starter.javascriptfunction work() { let s = 0; for (let i = 0; i < 1000; i++) s += i; return s; } const start = Date.now(); work(); const elapsed = Date.now() - start; if (elapsed > 1) throw new Error('too slow'); console.log('ok');Reveal the reference answer
reference.javascriptfunction work() { let s = 0; for (let i = 0; i < 1000; i++) s += i; return s; } const start = Date.now(); work(); const elapsed = Date.now() - start; if (elapsed > 100) throw new Error('too slow: ' + elapsed + 'ms'); console.log('ok');Authored expected output: ok
A 1ms budget is below clock resolution and normal variation, so it flakes. A 100ms budget is far above the real time but still catches a catastrophic regression such as an accidental nested loop, which is the point of the test.
Exercise 5Test
Write a test that proves a memoized function returns the cached value faster than the first call.
starter.javascriptfunction memoize(fn) { const cache = new Map(); return (arg) => { if (cache.has(arg)) return cache.get(arg); const result = fn(arg); cache.set(arg, result); return result; }; }Reveal the reference answer
reference.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); } const slow = memoize((n) => { let s = 0; for (let i = 0; i < n; i++) s += i; return s; }); const t1 = Date.now(); slow(200000); const first = Date.now() - t1; const t2 = Date.now(); slow(200000); const second = Date.now() - t2; assertEqual(second <= first, true, 'cached call not slower'); console.log('memoization performance verified');Authored expected output: memoization performance verified
The test compares the first call to the cached call on the same machine in the same run. The cached call should be at most as slow, which is a stable relative assertion rather than a brittle absolute budget.
Exercise 6Interview
In an interview, explain how you would test that a data-processing function scales acceptably.
Reveal the reference answer
reference.javascriptI would assert on growth rather than absolute time: run the function at n and 2n and check the ratio stays within a linear bound, which is stable across machines. I would also set a generous absolute ceiling to catch catastrophic regressions. For the system as a whole I would run a load test against a real environment and report p95 and p99 latency plus error rate, because averages hide the slow requests users feel. I keep these tests out of the fast unit path.The answer should combine growth-ratio assertions, a loose absolute ceiling, percentile-based load reporting, and separation from the fast suite.
Common misconceptions
#- A tight millisecond budget makes a performance test stronger.
- Average latency is the most useful load-test metric.
- Load tests can run inside a browser sandbox.
Follow-up practice
#- testing-ci-gates
- testing-test-strategy
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.