Memoized string prefix

Benchmark created on


Setup


const value = "123";
const cache = new Map();
const prefixWithMap = (map, prefix, key) => {
  let res = map.get(key);
  if (typeof res === "string") return res;
  res = `${prefix}${key}`;
  map.set(key, res);
  return res;
};

const createPrefixer = (prefix) => {
  const cache = Object.create(null); // No prototype overhead
  return (key) => {
    return cache[key] ??= `${prefix}${key}`;
  };
};

const prefixer = createPrefixer("prefix:");

const createPrefixProxy = (prefix) => {
  const cache = Object.create(null);
  return new Proxy({}, {
    get(_, key) {
      if (typeof key === 'string') {
        return cache[key] ??= `${prefix}${key}`;
      }
      return undefined;
    }
  });
};

const prefixProxy = createPrefixProxy("prefix:");

Test runner

Ready to run.

Testing in
TestOps/sec
Template string
`prefix:${value}`
ready
prefixWithMap
prefixWithMap(cache, "prefix:", value)
ready
prefixer
prefixer(value)
ready
prefixProxy
prefixProxy[value]
ready
Classic
"prefix:"+value
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.