Skip to content

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

@hobbitronics

Description

@hobbitronics

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`);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions