Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 38 / 68

Speeding up calculation with memoization (caching)

This lesson covers memoization in Objective-C, with the aim of understanding how to avoid repeating the same calculation.

Memoization stores a result once calculated and, when the same input arrives again, fetches it from storage instead of recalculating. Picture answering a repeated question from memory rather than working it out afresh.

The sample code uses an NSMutableDictionary as the cache and checks cache[key] each time slowSquare() is called. From the second identical input onwards you see the "Retrieved from cache" message.

A common early stumble is that a number used as a dictionary key has to be converted to an NSNumber. A primitive integer cannot be a key directly — you convert with the @(n) notation.

In professional work, caching recursive calculations and API results gives speed improvements you can feel.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)