micromatch / braces

Faster brace expansion for node.js. Besides being faster, braces is not subject to DoS attacks like minimatch, is more accurate, and has more complete support for Bash 4.3.
https://github.com/jonschlinkert
MIT License
207 stars 47 forks source link

Should this be using `Array.prototype.flat()` instead of `flatten` from /lib/utils #44

Open hobbitronics opened 2 weeks ago

hobbitronics commented 2 weeks ago

Just tested performance and seems Array.flat has better performance until a certain point, but then your implementation pulls ahead.

Array size = 1,000, depth = 5 % node testFlatPerf.js Custom Flatten Time: 0.14 ms Built-in Flatten Time: 0.12 ms

size = 10,000, depth = 5 % node testFlatPerf.js Custom Flatten Time: 2.35 ms Built-in Flatten Time: 1.02 ms

-- Performance change over somewhere in here --

size = 100,000, depth = 5 % node testFlatPerf.js Custom Flatten Time: 14.81 ms Built-in Flatten Time: 79.13 ms

size = 1,000,0000, depth = 5 % node testFlatPerf.js Custom Flatten Time: 127.74 ms Built-in Flatten Time: 768.20 ms

size = 100,000, depth = 1000 % node testFlatPerf.js Custom Flatten Time: 4.22 ms Built-in Flatten Time: 9.88 ms

Things come apart when I really ramped up the depth for both size = 100,000, depth = 10,000 node testFlatPerf.js /Users/mike/Desktop/testFlatPerf.js:18 if (Array.isArray(ele)) { ^

Here's the code I used to test

const { performance } = require('perf_hooks');

// Function to generate a large nested array for testing
const generateNestedArray = (size, depth) => {
  let array = Array(size).fill(1);
  for (let i = 0; i < depth; i++) {
    array = [array];
  }
  return array;
};

// Custom recursive flatten function
const customFlatten = (...args) => {
  const result = [];
  const flat = arr => {
    for (let i = 0; i < arr.length; i++) {
      const ele = arr[i];
      if (Array.isArray(ele)) {
        flat(ele);
        continue;
      }
      if (ele !== undefined) {
        result.push(ele);
      }
    }
    return result;
  };
  flat(args);
  return result;
};

// Built-in flat function
const builtInFlatten = (...args) => args.flat(Infinity);

// Test arrays
const testArray = generateNestedArray(1000, 5);

// Benchmark customFlatten
let start = performance.now();
customFlatten(testArray);
let customFlattenTime = performance.now() - start;

console.log(`Custom Flatten Time: ${customFlattenTime.toFixed(2)} ms`);

// Benchmark builtInFlatten
start = performance.now();
builtInFlatten(testArray);
let builtInFlattenTime = performance.now() - start;

console.log(`Built-in Flatten Time: ${builtInFlattenTime.toFixed(2)} ms`);
jonschlinkert commented 2 weeks ago

sure! if want to do a PR?

hobbitronics commented 2 weeks ago

https://github.com/micromatch/braces/pull/45