jsPerf.app is an online JavaScript performance benchmark test runner & jsperf.com mirror. It is a complete rewrite in homage to the once excellent jsperf.com now with hopefully a more modern & maintainable codebase.
jsperf.com URLs are mirrored at the same path, e.g:
https://jsperf.com/negative-modulo/2
Can be accessed at:
https://jsperf.app/negative-modulo/2
const data = [
{ id: 5, parent_id: 1 },
{ id: 1, parent_id: null },
{ id: 2, parent_id: 1 },
{ id: 6, parent_id: 1 },
{ id: 3, parent_id: 2 },
{ id: 8, parent_id: 1 },
{ id: 4, parent_id: 2 },
{ id: 7, parent_id: 3 }
];
function buildTreeMine(data) {
const tree = {};
const lookup = {};
for (const item of data) {
lookup[item.id] = item;
lookup[item.id].children = [];
}
for (const item of data) {
if (typeof lookup[item.parent_id] === 'undefined') {
tree[item.id] = item;
}
else {
lookup[item.parent_id].children.push(item);
}
}
return Object.values(tree);
}
const createTree = (data, parent_id = null) => {
// Create an empty array to hold the tree structure
let tree = [];
// Loop through the data to find the children of the parent_id
data.filter(item => item.parent_id === parent_id).forEach(item => {
// Recursively create the tree structure for the children
let children = createTree(data, item.id);
// If the children array is not empty, add it to the item
if (children.length) {
item.children = children;
}
// Add the item to the tree array
tree.push(item);
});
// Return the tree array
return tree;
};
const createTreeFAST = (data, parent_id = null) => {
let tree = [];
let children = [];
for (let item of data) {
if (item.parent_id === parent_id) {
children = createTreeFAST(data, item.id);
if (children.length) {
item.children = children;
}
tree.push(item);
}
}
return tree;
};
const createTreeFASTER = (data, parent_id = null) => {
let tree = [];
let children = [];
for (let i = 0; i < data.length; i++) {
if (data[i].parent_id === parent_id) {
children = createTreeFASTER(data, data[i].id);
if (children.length) {
data[i].children = children;
}
tree.push(data[i]);
}
}
return tree;
}
Ready to run.
Test | Ops/sec | |
---|---|---|
Mine |
| ready |
M1 |
| ready |
M2_FAST |
| ready |
M3_FASTER |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.