Created
March 20, 2013 22:00
-
-
Save jmikola/5208918 to your computer and use it in GitHub Desktop.
Benchmarking findOne() vs. find()->limit(1)->count(true)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$m = new MongoClient(); | |
$c = $m->test->foo; | |
$c->drop(); | |
$c->insert(['_id' => 1, 'x' => str_repeat('z', 1024*1024*4)]); | |
$c->insert(['_id' => 2, 'x' => str_repeat('z', 1024*1024*4)]); | |
$c->insert(['_id' => 3, 'x' => str_repeat('z', 1024*1024*4)]); | |
$c->insert(['_id' => 4, 'x' => str_repeat('z', 1024*1024*4)]); | |
$c->insert(['_id' => 5, 'x' => str_repeat('z', 1024*1024*4)]); | |
$t = function($iterations, $covered) use ($c) { | |
printf("Testing with%s covered index queries\n", $covered ? '' : 'out'); | |
$projection = $covered ? ['_id' => 1] : []; | |
printf(" %d iterations: findOne()\n", $iterations); | |
$start = microtime(true); | |
for ($i = 0; $i < $iterations; $i++) { | |
$id = $i % 5 + 1; | |
$c->findOne(['_id' => $id], $projection); | |
} | |
$end = microtime(true); | |
printf(" Total time: %f\n", $end - $start); | |
printf(" Average time: %f\n", ($end - $start) / $iterations); | |
printf(" %d iterations: find()->limit(1)->count(true)\n", $iterations); | |
$start = microtime(true); | |
for ($i = 0; $i < $iterations; $i++) { | |
$id = $i % 5 + 1; | |
$c->find(['_id' => $id], $projection)->limit(1)->count(true); | |
} | |
$end = microtime(true); | |
printf(" Total time: %f\n", $end - $start); | |
printf(" Average time: %f\n", ($end - $start) / $iterations); | |
}; | |
$t(1000, true); | |
$t(1000, false); | |
$t(10000, true); | |
$t(10000, false); | |
$t(100000, true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See: https://blog.serverdensity.com/checking-if-a-document-exists-mongodb-slow-findone-vs-find
Results with PHP 5.4.6, MongoDB driver 1.3.4, and MongoDB 2.2.3: