Skip to content

Instantly share code, notes, and snippets.

@dmitry-tuzenkov
Created November 20, 2023 20:33
Show Gist options
  • Save dmitry-tuzenkov/6a2e4e36c9518130270600c581f2dc04 to your computer and use it in GitHub Desktop.
Save dmitry-tuzenkov/6a2e4e36c9518130270600c581f2dc04 to your computer and use it in GitHub Desktop.
Memo Lesson
node ./none-memo && node ./memo
none_memo: 10.005s
memo: 989.782ms
node ./none-memo && node ./memo
none_memo: 9.897s
memo: 974.547ms
node ./none-memo && node ./memo
none_memo: 9.953s
memo: 978.818ms
const TIME_FLAG_MEMO = 'memo'
const toUpper = (str = '') => {
return String(str).toUpperCase()
}
const complexCalc = (str = '') => {
let result = ''
for (let i = 0; i < 10e5; i++) {
result = String(str).toUpperCase() + i
}
return result
}
const memoize = (fn) => {
const cacheMap = {}
return function (arg) {
const cacheKey = String(arg)
if (cacheMap[cacheKey]) {
// console.log("hit cache", cacheKey);
return cacheMap[cacheKey]
}
cacheMap[cacheKey] = fn(arg)
return cacheMap[cacheKey]
}
}
// This is our array of cases.
// it is need only for make a sequence to measure performance
const stringSize = 10
const strings = Array.from(
'abbcdeeefhhjjkkkabbcdeeefhhjjkkkabbcdeeefhhjjkkkabbcdeeefhhjjkkkabbcdeeefhhjjkkkabbcdeeefhhjjkkk'
).map((c) => c.repeat(stringSize))
// Experiment #2
console.time(TIME_FLAG_MEMO)
const memoized = memoize(toUpper)
const memoizedCalc = memoize(complexCalc)
for (const str in strings) {
memoized(strings[str])
memoizedCalc(strings[str])
}
console.timeEnd(TIME_FLAG_MEMO)
const TIME_FLAG_NONE_MEMO = 'none_memo'
const toUpper = (str = '') => {
return String(str).toUpperCase()
}
const complexCalc = (str = '') => {
let result = ''
for (let i = 0; i < 10e5; i++) {
result = String(str).toUpperCase() + i
}
return result
}
// This is our array of cases.
// it is need only for make a sequence to measure performance
const stringSize = 10
const strings = Array.from(
'abbcdeeefhhjjkkkabbcdeeefhhjjkkkabbcdeeefhhjjkkkabbcdeeefhhjjkkkabbcdeeefhhjjkkkabbcdeeefhhjjkkk'
).map((c) => c.repeat(stringSize))
// Experiment #1
console.time(TIME_FLAG_NONE_MEMO)
for (const str in strings) {
toUpper(strings[str])
complexCalc(strings[str])
}
console.timeEnd(TIME_FLAG_NONE_MEMO)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment