Christian
Christian•13mo ago

Efficiency of doing joins in JavaScript

So i was exploring convex, and following the react tutorial to get the gist of what convex provides. I ran into this bit of code.
export const list = query({
args: {},
handler: async (ctx) => {
// Grab the most recent messages.
const messages = await ctx.db.query("messages").order("desc").take(100);
const messagesWithLikes = await Promise.all(
messages.map(async (message) => {
// Find the likes for each message
const likes = await ctx.db
.query("likes")
.withIndex("byMessageId", (q) => q.eq("messageId", message._id))
.collect();
// Join the count of likes with the message data
return {
...message,
likes: likes.length,
};
})
);
// Reverse the list so that it's in a chronological order.
return messagesWithLikes.reverse().map((message) => ({
...message,
// Format smileys
body: message.body.replaceAll(":)", "😊"),
}));
},
});
export const list = query({
args: {},
handler: async (ctx) => {
// Grab the most recent messages.
const messages = await ctx.db.query("messages").order("desc").take(100);
const messagesWithLikes = await Promise.all(
messages.map(async (message) => {
// Find the likes for each message
const likes = await ctx.db
.query("likes")
.withIndex("byMessageId", (q) => q.eq("messageId", message._id))
.collect();
// Join the count of likes with the message data
return {
...message,
likes: likes.length,
};
})
);
// Reverse the list so that it's in a chronological order.
return messagesWithLikes.reverse().map((message) => ({
...message,
// Format smileys
body: message.body.replaceAll(":)", "😊"),
}));
},
});
How can this be efficient? No join, and simply looping over messages to get all required data? I get it's only querying 100 docs here but this seems to be a reverse of what I would be thinking about doing with something like postgresql or really anything besides firebase.
4 Replies
Michal Srb
Michal Srb•13mo ago
Hey @Christian, we run the function "inside" your database. When you join in a database like Postgres, it does essentially the same thing under the hood. The advantage with Convex is that you have total control over how a query is executed, whereas Postgres might or might not make optimizations leading to unpredictable performance.
Christian
ChristianOP•13mo ago
OOhhh, wow that's frickin cool
json
json•13mo ago
how does that work? is the js function compiled to something that runs in the db, and what is the db? o.o
Michal Srb
Michal Srb•13mo ago
Right now, the JS is run in our own runtime built on top of V8 and the database is built on top of RDS and specialized indexes for search/vector search. These are internal implementation details though, and they might change as Convex matures, further improving performance. We're focused on providing the right DX (developer experience), so that you don't have to worry about the underlying infrastructure. That's the beauty of Convex!

Did you find this page helpful?