I've written the following simple code to test the performance difference between Rust and Python.
Here's the Rust version:
#![allow(unused)]
use mongodb::{sync::Client, options::ClientOptions, bson::doc, bson::Document};
fn cursor_iterate()-> mongodb::error::Result<()>{
// setup
let mongo_url = "mongodb://localhost:27017";
let db_name = "MYDB";
let collection_name = "MYCOLLECTION";
let client = Client::with_uri_str(mongo_url)?;
let database = client.database(db_name);
let collection = database.collection::<Document>(collection_name);
// println!("{:?}", collection.count_documents(None, None));
let mut cursor = collection.find(None, None)?;
let mut count = 0;
for result in cursor {
count += 1;
}
println!("Doc count: {}", count);
Ok(())
}
fn main() {
cursor_iterate();
}
This simple cursor iterator takes around 8 seconds with time cargo run
:
Finished dev [unoptimized + debuginfo] target(s) in 0.05s
Running `target/debug/bbson`
Doc count: 14469
real 0m8.545s
user 0m8.471s
sys 0m0.067s
Here's the equivalent Python code:
import pymongo
def main():
url = "mongodb://localhost:27017"
db = "MYDB"
client = pymongo.MongoClient(url)
coll = client.get_database(db).get_collection("MYCOLLECTION")
count = 0
for doc in coll.find({}):
count += 1
print('Doc count: ', count)
if __name__ == "__main__":
main()
It takes about a second to run with time python3 test.py
:
Doc count: 14469
real 0m1.079s
user 0m0.603s
sys 0m0.116s
So what makes the Rust code this slow? Is it the sync? the equivalent C++ code takes about 100ms.
EDIT: After running in the --release
mode, I get:
Doc count: 14469
real 0m0.928s
user 0m0.871s
sys 0m0.041s
still barely matching the python version.