Skip to content

Instantly share code, notes, and snippets.

@jeovazero
Created November 21, 2019 17:15
Show Gist options
  • Save jeovazero/35cf8a22054241dc90017db4d7dad37d to your computer and use it in GitHub Desktop.
Save jeovazero/35cf8a22054241dc90017db4d7dad37d to your computer and use it in GitHub Desktop.
Partition in Node v12
const R = require('ramda')
const _ = require('lodash')
const NS_PER_SEC = 1e9
const NS_PER_MILLIS = 1e6
function partitionV2(cond, data) {
const accepted = []
const rejected = []
const len = data.length
let elem
let i = 0
while(i < len) {
elem = data[i]
if (cond(elem)) {
accepted.push(elem)
} else {
rejected.push(elem)
}
++i
}
return [accepted, rejected]
}
function singleRun(fn) {
const startTime = process.hrtime()
fn()
const duration = process.hrtime(startTime)
// result in nanos
return duration[0] * NS_PER_SEC + duration[1]
}
const add = (a, b) => a + b
function run(fn, n) {
const m = n
const runs = []
while (0 <-- n) {
runs.push(singleRun(fn))
}
// result in millis
return runs.reduce(add) / NS_PER_MILLIS
}
const isOdd = x => x % 2 !== 0
const runTests = (cond, size, times) => {
const data = R.range(1, size + 1)
const funcs = [
['Ramda', () => R.partition(cond, data)],
['Lodash', () => _.partition(data, cond)],
['Vanilla', () => partitionV2(cond, data)]
]
console.log(`\nArray :: size ${size} :: times ${times}:\n`)
funcs.forEach(([libName, func]) => {
console.log(`-- ${libName}:\t${run(func, times)} millis`)
})
console.log('\n')
}
runTests(isOdd, 1000000, 100)
runTests(isOdd, 10000, 1000)
runTests(isOdd, 100, 10000)
{
"name": "performance",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"lodash": "4.17.15",
"ramda": "0.26.1"
}
}
Array :: size 1000000 :: times 100:
-- Ramda: 5604.457264 millis
-- Lodash: 2229.485391 millis
-- Vanilla: 2074.14233 millis
Array :: size 10000 :: times 1000:
-- Ramda: 462.500396 millis
-- Lodash: 111.673181 millis
-- Vanilla: 94.139585 millis
Array :: size 100 :: times 10000:
-- Ramda: 68.294782 millis
-- Lodash: 18.926197 millis
-- Vanilla: 9.33258 millis
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment