Split array into smaller chunks

Benchmark created on


Description

Compare splitting an array into smaller chunks using splice, slice and reduce, without modifying the original array.

Setup

const list = Array.from({ length: 10_000 }, Math.random)
const chunkSize = 10
const chunks = []

Test runner

Ready to run.

Testing in
TestOps/sec
Array.prototype.slice()
for (let i = 0; i < list.length; i += chunkSize) {
	chunks.push(list.slice(i, chunkSize + i))
}
ready
Array.prototype.splice()
const listCopy = list.slice(0)
while (listCopy.length) {
	chunks.push(listCopy.splice(0, chunkSize))
}
ready
Array.prototype.reduce()
list.reduce((acc, item, index) => {
	if (index % chunkSize === 0) {
		acc.push([item])
	} else {
		acc[acc.length-1].push(item)
	}
	return chunks
}, chunks)
ready

Revisions

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