EasyExpediaUberLinkedin

Memoize II

Prompt

In the first part of the Memoize challenge, you built a function that caches results to avoid redundant computation. But how do you actually prove it's faster?

Your task is to use console.time() and console.timeEnd() to measure the execution time of a memoized function across multiple calls and demonstrate the performance benefit.

Given the memoize function and an expensive square function (that uses nested loops instead of n * n), measure how long each call takes and observe the difference between the first call and subsequent cached calls.

Playground

This question has no automated test cases. Performance timing with console.time produces different values on every run depending on your machine, so it can't be reliably asserted in tests. Verify your solution by checking the console output -- the first call should take noticeably longer than the subsequent cached calls.

Hint 1

console.time('label') starts a timer, and console.timeEnd('label') stops it and prints how long it took. The label string must match exactly between the two calls.

Hint 2

Wrap each memoizedSquare(140) call between a console.time and console.timeEnd pair with a unique label like 'Call 1', 'Call 2', etc.

Solution

Explanation

How do you measure performance in JavaScript?

JavaScript gives us a simple built-in stopwatch: console.time() and console.timeEnd().

You start the stopwatch with a label, run some code, and then stop the stopwatch with the same label. The browser prints how many milliseconds elapsed.

console.time('my-operation');
// ... some code runs here ...
console.timeEnd('my-operation');
// Output: my-operation: 12.34ms

What does this tell us about memoization?

When you run the solution above, you'll see something like:

Call 1: 2.5ms ← Actually computed (cache miss)
Call 2: 0.01ms ← Returned from cache (cache hit)
Call 3: 0.01ms ← Returned from cache (cache hit)

The first call takes real time because the square function actually runs its nested loops. The second and third calls are nearly instant because the memoized function finds the result in the cache and returns it without ever running square again.

This is the whole point of memoization: trade memory for speed. You store results so you never compute the same thing twice.

A Cooking Analogy

Imagine you're making pasta from scratch for the first time. You knead the dough, roll it out, cut it into shapes -- it takes 45 minutes. But you're smart, so you make extra and freeze it.

The next time you want pasta, you just grab it from the freezer and boil it -- 5 minutes instead of 45.

That's exactly what console.time is proving here. The first call is "making pasta from scratch." Every call after that is "grabbing it from the freezer."

  • console.time('Making Pasta') -- Start the stopwatch
  • Cook the pasta (run your code)
  • console.timeEnd('Making Pasta') -- Stop the stopwatch and see the time