DEV Community

Discussion on: In defense of JavaScript oddities

Collapse
 
qm3ster profile image
Mihail Malo

Truly, for example when you index into a hashmap object with another object instead of its property.

const cache = Object.create(null)
const uselessCache = (arg) => {
  const cached = cache[arg.id]
  if (cached) return cached
  return cached[arg/* [object Object] */] = expensive(arg)
}
const uselessCacheNowWithMoreWastedMemory = (arg) => {
  const cached = cache[arg/* [object Object] */]
  if (cached) return cached
  return cached[arg.id] = expensive(arg)
}
const actualCollision = (arg) => {
  const cached = cache[arg/* [object Object] */]
  if (cached) return cached
  return cached[arg/* [object Object] */] = expensive(arg)
}

Next time on Mythbusters: an even bigger waste of memory by passing these objects to an ES6 Map as keys, meaning they themselves cannot be garbage collected and generating infinite duplicate cached values. What fun!