Created
January 11, 2024 02:50
-
-
Save brunofunnie/c923b4df093a329be2c7be1b1c43a769 to your computer and use it in GitHub Desktop.
Javascript Object to Array conversion performance tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based/copied on/from article: https://dev.to/petrtcoi/performance-of-the-spread-operator-2bpk | |
// npm install immer immutable ramba lodash @faker-js/faker | |
// node app.js | |
const _ = require('lodash'); | |
const R = require('ramda'); | |
const { Map } = require('immutable') | |
const { produce } = require('immer'); | |
const { faker } = require('@faker-js/faker') | |
function funcSpread() { | |
return fakeData.reduce((acc, { key, name }) => { | |
return { ...acc, [key]: name }; | |
}, {}); | |
} | |
function funcMutate() { | |
return fakeData.reduce((acc, { key, name }) => { | |
acc[key] = name | |
return acc | |
}, {}) | |
} | |
function funcLodash() { | |
return fakeData.reduce((acc, { key, name }) => { | |
return _.set(acc, key, name) | |
}, {}) | |
} | |
function funcImmutable() { | |
return fakeData.reduce((acc, { key, name }) => { | |
return acc.set(key, name) | |
}, Map({})) | |
} | |
function funcImmer() { | |
return fakeData.reduce((acc, { key, name }) => { | |
return produce(acc, draft => { draft[key] = name }) | |
}, {}) | |
} | |
function funcImmer2() { | |
return produce({}, draft => { | |
fakeData.forEach(({ key, name }) => { | |
draft[key] = name | |
}) | |
}) | |
} | |
function funcRamda() { | |
return fakeData.reduce((acc, { key, name }) => { | |
return R.assoc(key, name, acc) | |
}, {}) | |
} | |
// Generate fake data | |
console.time('Generating fake data'); | |
const fakeData = [] | |
for (let i = 0; i < 9999; i++) { | |
fakeData.push({ key: faker.string.uuid(), name: faker.word.words() }) | |
} | |
console.timeEnd('Generating fake data'); | |
console.time("Spread execution time"); | |
funcSpread(); | |
console.timeEnd("Spread execution time"); | |
console.time("Mutate execution time"); | |
funcMutate(); | |
console.timeEnd("Mutate execution time"); | |
console.time("Lodash execution time"); | |
funcLodash(); | |
console.timeEnd("Lodash execution time"); | |
console.time("Immutable execution time"); | |
const mapData = funcImmutable() | |
const object = mapData.toObject() | |
console.timeEnd("Immutable execution time"); | |
console.time("Immer execution time"); | |
funcImmer(); | |
console.timeEnd("Immer execution time"); | |
console.time("Immer2 execution time"); | |
funcImmer2(); | |
console.timeEnd("Immer2 execution time"); | |
console.time("Ramda execution time"); | |
funcRamda(); | |
console.timeEnd("Ramda execution time"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment