Skip to content

Instantly share code, notes, and snippets.

@avaly
Created August 23, 2018 12:25
Show Gist options
  • Save avaly/14c4521d45ccd173b72a8044bdc1888c to your computer and use it in GitHub Desktop.
Save avaly/14c4521d45ccd173b72a8044bdc1888c to your computer and use it in GitHub Desktop.
benchmark-propsOrId.js
const _ = require('lodash');
const mongoose = require('mongoose');
const Benchmark = require('benchmark');
const { ObjectId } = mongoose.Types;
const isObjectId = (id) => id instanceof ObjectId;
function withCond(props, value) {
return _.cond([
[isObjectId, _.toString],
[_.isObject, _.partialRight(_.pick, props)],
[_.stubTrue, _.identity]
])(value);
}
function vanilla(props, value) {
if (isObjectId(value)) {
return value.toString();
}
if (_.isObject(value)) {
return _.pick(value, props);
}
return value;
}
const ID = new ObjectId('01234567890123456789abcd');
const OBJECT = {
foo: 'bar',
_id: ID
};
const suite = new Benchmark.Suite();
suite
.add('withCond', () => {
withCond(ID.toString());
withCond(['foo', '_id'], OBJECT);
withCond(['foo', '_id'], ID);
})
.add('vanilla', () => {
vanilla(ID.toString());
vanilla(['foo', '_id'], OBJECT);
vanilla(['foo', '_id'], ID);
})
.on('cycle', (event) => {
console.log(String(event.target));
})
.run();
@avaly
Copy link
Author

avaly commented Aug 23, 2018

$ node benchmark-propsOrId.js 
withCond x 139,858 ops/sec ±1.43% (91 runs sampled)
vanilla x 1,138,312 ops/sec ±0.92% (93 runs sampled)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment