Testing with ethers.js in Blockchain / Solidity - Time & Space Complexity
When testing smart contracts with ethers.js, it's important to know how the time to run tests changes as the number of tests or contract calls grows.
We want to understand how the test execution time scales when we add more test cases or interact more with the blockchain.
Analyze the time complexity of the following ethers.js test code snippet.
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("SimpleContract", function () {
it("should return correct value", async function () {
const contract = await ethers.getContractFactory("SimpleContract").then(factory => factory.deploy());
await contract.deployed();
for (let i = 0; i < 100; i++) {
const value = await contract.getValue(i);
expect(value).to.equal(i * 2);
}
});
});
This code deploys a contract and calls a function 100 times in a loop, checking the returned value each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop calling
contract.getValue(i)100 times. - How many times: Exactly 100 times in this example, but this number can grow with test size.
As the number of calls in the loop increases, the total test time grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 contract calls |
| 100 | 100 contract calls |
| 1000 | 1000 contract calls |
Pattern observation: Doubling the number of calls roughly doubles the total execution time.
Time Complexity: O(n)
This means the test time grows linearly with the number of contract calls in the loop.
[X] Wrong: "Adding more calls inside the test loop won't affect test time much because calls are fast."
[OK] Correct: Each contract call involves communication with the blockchain simulator or network, which takes time. More calls add up and increase total test time linearly.
Understanding how test execution time grows helps you write efficient tests and shows you can think about performance beyond just code correctness.
"What if we batch multiple calls into one contract function instead of calling individually? How would the time complexity change?"