Last active
August 29, 2015 14:16
-
-
Save banderson623/6ac34f08f58a99b6f0be to your computer and use it in GitHub Desktop.
Simple example of how caching works
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A place to store results | |
var memory = {}; | |
var primesUpTo = function(maxNumber){ | |
// set up something that is very unique to this request | |
var cacheKey = 'primes:max:' + maxNumber; | |
// Get the result from memory | |
var result = memory[cacheKey]; | |
// check if have a stored version of this in memory | |
// if the result was `undefined` we have yet to request it. | |
var isPresent = typeof(result) !== "undefined"; | |
if (!isPresent){ | |
// We have not saved the results yet... this is a "Cache Miss" | |
console.log("cache miss on " + maxNumber); | |
// here we are making our "expensive call" (aka something that takes a lot of time) | |
result = _getPrimes(maxNumber); | |
// Now we want to store this with our cache key | |
memory[cacheKey] = result; | |
} else { | |
console.log("Cache Hit " + maxNumber); | |
} | |
// This was either set during the cache HIT (line 10) or in the cache MISS (line 21) | |
return result; | |
}; | |
// STOP READING HERE ................ | |
// this is just a function that takes a while to return the result | |
// calculating primes | |
var _getPrimes = function(max) { | |
var sieve = [], i, j, primes = [];for (i = 2; i <= max; ++i) {if (!sieve[i]) {primes.push(i);for (j = i << 1; j <= max; j += i) {sieve[j] = true;}}}return primes; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From @ckolderup
More complex caching infrastructures: