Async vs Sync NodeJs: A Simple Benchmark

Async and sync are probably two of the most heard words among javascript developers, they refer to asynchronous and synchronous programming respectively. Asynchronous programming in javascript can be done using callbacks, Promise, and async and await.

Javascript handles asynchronous tasks with the help of event loop. We know that it increases performance and doesn't block the rest of the code. But everything is theoretical, how do we know is it actually increases performance?

By doing some benchmarks!!

In this article, we won't discuss how to program asynchronously or synchronously, instead, we are going to run some benchmarks against sync and async methods.

For the test case, we are going to use the bcrypt package which has sync and async methods to hash a given string. We also need express.

let's start by installing the dependencies.

yarn add express bcryp

The following script can be used for benchmarking.

import express from 'express'import bcrypt from 'bcrypt'const app = express()  app.get('/sync', (req, res) => {let hashed = bcrypt.hashSync('secret', 10)return res.send(hashed)})  app.get('/async', async (req, res) => {let hashed = await bcrypt.hash('secret', 10)return