immutable js

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
native
 function stringifyJSONdeterministic(args){
  if (args === null || typeof args !== "object") {
    return JSON.stringify(args)
  }

  if (Array.isArray(args)) {
    // The order of arrays is preserved
    return `[${args.map((arg) => stringifyJSONdeterministic(arg)).join(",")}]`
  }
  if (args instanceof Set) {
    Debug.error("Could not stringify in a deterministic manner", args)
  }

  const sortedKeys = (Object.keys(args))
    .filter((key) => args[key] !== undefined)
    .sort()
  if (sortedKeys.length === 0) {
    return "{}"
  }
  let result = "{"
  for (const key of sortedKeys) {
    result += `"${String(key)}": ${stringifyJSONdeterministic(args[key])},`
  }
  return `${result.slice(0, -1)}}` // trim training comma from last item, append final `}`
}

const key = { foo: "bar", bar: "baz"}
const keyStr = stringifyJSONDeterministic(key);
const cache = {};
cache[key] = 1;

console.log(cache[stringifyJSONDeterministic({ foo: "bar", bar: "baz"})])

ready
native2
 function stringifyJSONdeterministic(args){
  if (args === null || typeof args !== "object") {
    return JSON.stringify(args)
  }

  if (Array.isArray(args)) {
    // The order of arrays is preserved
    return `[${args.map((arg) => stringifyJSONdeterministic(arg)).join(",")}]`
  }
  if (args instanceof Set) {
    Debug.error("Could not stringify in a deterministic manner", args)
  }

  const sortedKeys = (Object.keys(args))
    .filter((key) => args[key] !== undefined)
    .sort()
  if (sortedKeys.length === 0) {
    return "{}"
  }
  let result = "{"
  for (const key of sortedKeys) {
    result += `"${String(key)}": ${stringifyJSONdeterministic(args[key])},`
  }
  return `${result.slice(0, -1)}}` // trim training comma from last item, append final `}`
}

const key = { foo: "bar", bar: "baz"}
const keyStr = stringifyJSONDeterministic(key);
const cache = {};
cache[key] = 1;

console.log(cache[stringifyJSONDeterministic({ foo: "bar", bar: "baz"})])

ready

Revisions

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