javascript - MongoDB: forEach vs fetch + each -


when want iterate on set of documents stored in mongodb meteor app, can use either

db.collection.find( ... ).foreach( function f( doc ){ ... }) 

or

var docs = db.collection.find( ... ).fetch(); _.each( docs, function f( doc ){ ... }); // using underscore.js 

which way preferable performance point of view? cons , pros exist both choices?

the 2 statements same thing @ core api level, cursor , tranform results. there 1 "core" difference performance:

  • .foreach() tranform cursor results "one @ time" , process iterator function provided.

  • .fetch() on other hand gets "array" cursor "all @ once" means "in memory" in 1 hit.

so no matter what, neither "faster" @ doing "core" operation of fetching cursor of query. however, not evaluating "expression" on each cursor iteration "may be" faster, .fetch() might win "little" here.

the great big catch of course "everything in memory", there "overhead" of doing consider. well, @ time of .fetch() _.each() yet processed, saying goes. "what "gain" on swings "loose" on roundabouts".

without full benchmarking of specific cases, "timings" similar. , generic benchmarking next useless unless applies size of data sets working with.

the general case therefore comes out, "about same", using .fetch() going consume more memory iterating cursor start.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -