0
0
Blockchain / Solidityprogramming~5 mins

Web3.js vs ethers.js in Blockchain / Solidity - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Web3.js vs ethers.js
O(n)
Understanding Time Complexity

When working with blockchain libraries like Web3.js and ethers.js, it's important to understand how their operations scale as you interact with the blockchain.

We want to see how the time to complete tasks grows when using these libraries with larger inputs or more complex calls.

Scenario Under Consideration

Analyze the time complexity of fetching multiple account balances using Web3.js and ethers.js.


// Using Web3.js
const balances = [];
for (let i = 0; i < accounts.length; i++) {
  const balance = await web3.eth.getBalance(accounts[i]);
  balances.push(balance);
}

// Using ethers.js
const balances = await Promise.all(
  accounts.map(account => provider.getBalance(account))
);
    

This code fetches the balance for each account from the blockchain using two different libraries.

Identify Repeating Operations

Look at what repeats as input grows.

  • Primary operation: Fetching balance for each account.
  • How many times: Once per account, so as many times as there are accounts.
How Execution Grows With Input

As the number of accounts increases, the number of balance fetches grows the same way.

Input Size (n)Approx. Operations
1010 balance fetches
100100 balance fetches
10001000 balance fetches

Pattern observation: The work grows directly with the number of accounts.

Final Time Complexity

Time Complexity: O(n)

This means the time to get all balances grows in a straight line as you add more accounts.

Common Mistake

[X] Wrong: "Using Promise.all in ethers.js makes the operation constant time regardless of input size."

[OK] Correct: Even though Promise.all runs requests in parallel, each balance still needs to be fetched, so total work still grows with the number of accounts.

Interview Connect

Understanding how blockchain library calls scale helps you write efficient code and explain your choices clearly in conversations.

Self-Check

What if we batch multiple balance requests into a single call? How would the time complexity change?