Array Join vs Concat

Benchmark created on


Setup

const input = {
    color: {
      primary: {
        $value: "#3490dc",
        $type: "color",
      },
      secondary: {
        $value: "#ffed4a",
        $type: "color",
      },
      neutral: {
        light: {
          thing: {
            $value: "#f5f5f5",
            $type: "color",
          }
        },
        dark: {
          $value: "#333333",
          $type: "color",
        },
      },
      otherneutral: {
        light: {
          thing: {
            $value: "#f5f5f5",
            $type: "color",
          }
        },
        dark: {
          $value: "#333333",
          $type: "color",
        },
      },
    }
};

const traverseTokenGroup = (jsonObj, label, output) => {
  if (!jsonObj) return "";
  Object.entries(jsonObj).forEach(([key, value]) => {
    if (key === "$value" || key === "$type") {
      return;
    }
    if (typeof value === 'object') {
      if (Object.keys(value).includes("$value")) {
        const leafNode = value;
        output.push(`    ${label}-${key}: ${leafNode.$value};`);
      }
      traverseTokenGroup(value, `${label}-${key}`, output);
    }
  });
  return output.join("\n");
};

const traverseTokenGroup2 = (obj, currentLabel) => {
    return Object.entries(obj).reduce((acc, [key, value]) => {
      if (key === "$value" || key === "$type") {
        return acc;
      }
      if (typeof value === 'object') {
        if (Object.keys(value).includes("$value")) {
          acc += `    ${currentLabel}-${key}: ${value.$value};\n`;
        }
        acc += traverseTokenGroup2(value, `${currentLabel}-${key}`);
      }
      return acc;
    }, '');
  };
  
const enc = new TextEncoder()

Test runner

Ready to run.

Testing in
TestOps/sec
Array Join
const r = traverseTokenGroup(input, '-', [])
const b = enc.encode(r)
ready
String Concat
const r = traverseTokenGroup2(input, '-')
const b = enc.encode(r)
ready

Revisions

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