MongoDB:forEach vs提取+每个 [英] MongoDB: forEach vs fetch + each

查看:131
本文介绍了MongoDB:forEach vs提取+每个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想通过Meteor应用程序遍历MongoDB中存储的某些文档集时,我可以使用

When I want to iterate over some set of documents stored in MongoDB from my Meteor app, I can use either

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

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

从性能角度来看,哪种方法更可取?两种选择都有哪些利弊?

Which way is preferable from performance point of view? What cons and pros exist for both choices?

推荐答案

这两个语句在核心API级别上基本上做相同的事情,即获取游标并转换结果.但是,性能之间存在一个核心"差异:

The two statements do basically the same thing at the core API level, which is get the cursor and tranform the results. There is however one "core" difference about performance:

  • .forEach() 将一次一次"转换光标结果并处理它提供的迭代器功能.

  • .forEach() will tranform the cursor results "one at a time" and process the iterator function it is provided.

.fetch() 从光标全部"获得数组",这意味着一次命中全部在内存中".

.fetch() on the other hand gets the "array" from the cursor "all at once" which means it is all "in memory" in one hit.

因此,无论如何,实际上都不是更快"地执行从查询的游标中提取数据的核心"操作.但是,不对每个游标迭代求值表达式"可能会快一些",因此.fetch()在这里可能会赢得小".

So no matter what, neither is actually "faster" at doing the "core" operation of fetching from the cursor of the query. However, not evaluating an "expression" on each cursor iteration "may be" slightly faster, so .fetch() might win a "little" here.

当然,最大的收获是现在所有的东西都在记忆中",因此需要考虑这一点的开销".俗话说,在.fetch()时,_.each()尚未处理. 您在秋千上获得"的东西在回旋处可能松动""..

The great big catch of course is "everything is now in memory", so there is the "overhead" of doing that to consider. As well, at the time of .fetch() the _.each() is yet to be processed, so as the saying goes. "What you "gain" on the swings you likely "loose" on the roundabouts".

如果没有对特定案例进行全面的基准测试,那么时机"可能会相似.通用基准测试几乎是无用的,除非它专门适用于您正在使用的数据集的大小.

Without full benchmarking of specific cases, the "timings" are likely to be similar. And generic benchmarking is next to useless unless it specifically applies the size of data sets you are working with.

因此出现了一般情况,大约相同" ,但是使用.fetch()会消耗更多的内存,而不仅仅是从头开始遍历光标.

The general case therefore comes out, "About the same", However using .fetch() is going to consume more memory than just iterating a cursor from the start.

这篇关于MongoDB:forEach vs提取+每个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆