Skip to content

Instantly share code, notes, and snippets.

@jmikola
Created March 20, 2013 22:00
Show Gist options
  • Save jmikola/5208918 to your computer and use it in GitHub Desktop.
Save jmikola/5208918 to your computer and use it in GitHub Desktop.
Benchmarking findOne() vs. find()->limit(1)->count(true)
<?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);
@jmikola
Copy link
Author

jmikola commented Mar 20, 2013

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:

$ php foo.php 
Testing with covered index queries
 1000 iterations: findOne()
  Total time: 0.086271
  Average time: 0.000086
 1000 iterations: find()->limit(1)->count(true)
  Total time: 0.184013
  Average time: 0.000184
Testing without covered index queries
 1000 iterations: findOne()
  Total time: 9.910719
  Average time: 0.009911
 1000 iterations: find()->limit(1)->count(true)
  Total time: 0.149288
  Average time: 0.000149
Testing with covered index queries
 10000 iterations: findOne()
  Total time: 1.182638
  Average time: 0.000118
 10000 iterations: find()->limit(1)->count(true)
  Total time: 1.473222
  Average time: 0.000147
Testing without covered index queries
 10000 iterations: findOne()
  Total time: 90.084688
  Average time: 0.009008
 10000 iterations: find()->limit(1)->count(true)
  Total time: 1.458132
  Average time: 0.000146
Testing with covered index queries
 100000 iterations: findOne()
  Total time: 11.067744
  Average time: 0.000111
 100000 iterations: find()->limit(1)->count(true)
  Total time: 10.108605
  Average time: 0.000101

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