chunked array (v2)

Revision 2 of this benchmark created on


Description

https://stackoverflow.com/questions/78191924/i-need-to-chunk-an-array-into-smaller-arrays-of-a-specified-size-and-im-unsure

Setup

let arr = [...new Array(25000)].map(i => Math.floor(Math.random() * 25000));

const chunk = (arr, size) => {
    const chunkedArr = [];
    let i = 0;
    while(i < arr.length) {
        chunkedArr.push(arr.splice(0, size))
    }
    return chunkedArr;
};

const chunk2 = (arr, size) => {
	if (arr.length === 0 || size <= 0) {
        return [];
    }
    const chunkedArr = [];
    let i = 0;
    while(i < arr.length) {
        chunkedArr.push(arr.splice(0, size))
    }
    return chunkedArr;
};

const chunkArray = (arr, size) => {
    // Check if the array is empty or if size is not positive
    if (arr.length === 0 || size <= 0) {
        return [];
    }

    // Calculate the number of chunks needed
    const numChunks = Math.ceil(arr.length / size);

    // Create an array to store the chunked arrays
    const chunkedArray = [];

    // Loop through the array and push chunks into the chunkedArray
    for (let i = 0; i < numChunks; i++) {
        const start = i * size;
        const end = start + size;
        chunkedArray.push(arr.slice(start, end));
    }

    return chunkedArray;
}



const chunkArray2 = (arr, size) => {
    

    // Calculate the number of chunks needed
    const numChunks = Math.ceil(arr.length / size);

    // Create an array to store the chunked arrays
    const chunkedArray = [];

    // Loop through the array and push chunks into the chunkedArray
    for (let i = 0; i < numChunks; i++) {
        const start = i * size;
        const end = start + size;
        chunkedArray.push(arr.slice(start, end));
    }

    return chunkedArray;
}

Teardown

arr = null;

Test runner

Ready to run.

Testing in
TestOps/sec
chunk
chunk(arr, 4000)
ready
chunk2
chunk2(arr, 4000)
ready
chunkArray
chunkArray(arr, 4000)
ready
chunkArray2
chunkArray2(arr, 4000)
ready

Revisions

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