Yaron Levi
Yaron Levi

Reputation: 13077

RethinkDB - coerceTo("array") vs cursor performance?

Consider a query, which I know will return no more then one result. Is there any performance penalty if instead of this:

r.table('users').filter({facebookUserId:facebookUserId}).
    run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            if (err) throw err;
            //return the value
        });
    });

I use this:

const res = await r.table('users')
            .filter({facebookUserId:facebookUserId})
            .coerceTo("array")
            .run(connection);

I am specifically referring to the coerceTo() command vs the cursor.

Upvotes: 2

Views: 200

Answers (1)

Stock Overflaw
Stock Overflaw

Reputation: 3321

I would do the following:

  • create an index on facebookUserId so that I can use r.table('users').getAll(myInput, {index: 'facebookUserId'}), avoiding parsing all the documents (waaaaay faster)
  • not call sequence.coerceTo() because it's one more step in a probably distributed, scalable DB
  • use cursor.next() as it directly provides the next element as soon as it's ready, instead of cursor.toArray() which, in this case, will do the same plus checking the stream has ended (so it must be slower)
  • call cursor.close() as soon as I enter cursor.next() to directly free resources
  • adapt my code so that I don't even need to access an array's first element, since cursor.next() didn't uselessly encapsulate my document in an array

In the end: r.table('users').getAll(facebookUserId, {index: 'facebookUserId'}) .run(connection, function(err, cursor) { if (err) throw err; cursor.next(function(err, item) { cursor.close() if (err) throw err; //do something with item instead of result[0]; }); }); One more thing: cursor.next() behaviour can be done using cursor.each() with return false. However, should the methods vary in performance (I dont know but a documentation note tends to prefer each), we still need to wait the return of cursor.each() before closing the cursor, which mustn't be the best performance profile, all things considered.

Hope this helps!

Upvotes: 3

Related Questions