Skip to content

Instantly share code, notes, and snippets.

@crapthings
Last active January 4, 2018 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crapthings/12b0ef99d9ed75bd3dc35fab577afda4 to your computer and use it in GitHub Desktop.
Save crapthings/12b0ef99d9ed75bd3dc35fab577afda4 to your computer and use it in GitHub Desktop.
const _ = require('lodash')
const faker = require('faker')
console.time('make data')
const seed = 20000
const authors = _.times(seed, n => ({
id: 'a' + n,
name: faker.name.findName(),
}))
const posts = _.times(seed * 10, n => ({
id: n,
authorId: 'a' + _.random(seed),
title: faker.lorem.sentence(),
context: faker.lorem.paragraph(),
}))
console.timeEnd('make data')
console.time('map posts 1')
const postsWithAuthor = posts.map(post => ({
author: authors.find(author => author.id === post.authorId),
...post
}))
console.timeEnd('map posts 1')
console.log(postsWithAuthor[0])
console.time('map posts 2')
const postsWithAuthor2 = posts.map(post => ({
author: authors[post.authorId] || authors.find(author => {
if (author.id === post.authorId)
return true
authors[author.id] = author
return false
}),
...post
}))
console.timeEnd('map posts 2')
console.log(postsWithAuthor2[0])
console.time('map posts 3')
let authorsCache = {}
const postsWithAuthor3 = []
for (author of authors) {
authorsCache[author.id] = author
}
// for (i = 0; i < posts.length; i++) {
// const post = posts[i]
// postsWithAuthor3[i] = {
// author: authorsCache[post.authorId],
// ...post // slow
// }
// }
for (i = 0; i < posts.length; i++) {
const post = posts[i]
post.author = authorsCache[post.authorId]
postsWithAuthor3[i] = post
}
console.timeEnd('map posts 3')
console.log(postsWithAuthor3[0])
make data: 2753.530ms
map posts 1: 34069.888ms
{ author: { id: 'a13127', name: 'Gail Terry' },
id: 0,
authorId: 'a13127',
title: 'Iure modi voluptates sit placeat fuga voluptatem magnam.',
context: 'Aliquid sit maxime omnis vel laborum. Architecto quasi nesciunt dolor est iure hic facere. Possimus cum blanditiis voluptas vel nemo hic.' }
map posts 2: 432.376ms
{ author: { id: 'a13127', name: 'Gail Terry' },
id: 0,
authorId: 'a13127',
title: 'Iure modi voluptates sit placeat fuga voluptatem magnam.',
context: 'Aliquid sit maxime omnis vel laborum. Architecto quasi nesciunt dolor est iure hic facere. Possimus cum blanditiis voluptas vel nemo hic.' }
map posts 3: 85.246ms
{ id: 0,
authorId: 'a13127',
title: 'Iure modi voluptates sit placeat fuga voluptatem magnam.',
context: 'Aliquid sit maxime omnis vel laborum. Architecto quasi nesciunt dolor est iure hic facere. Possimus cum blanditiis voluptas vel nemo hic.',
author: { id: 'a13127', name: 'Gail Terry' } }
[nodemon] clean exit - waiting for changes before restart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment