Writing test cases in Blockchain / Solidity - Time & Space Complexity
When writing test cases for blockchain code, it's important to know how the time to run tests grows as you add more cases.
We want to understand how the number of tests affects the total time needed to check the code.
Analyze the time complexity of the following test-running code snippet.
function runTests(tests) {
for (let i = 0; i < tests.length; i++) {
tests[i].execute();
}
}
This code runs each test case one by one from a list of tests.
Look for loops or repeated actions.
- Primary operation: Calling
execute()on each test case. - How many times: Once for each test in the list.
As you add more tests, the total time grows in a simple way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to execute() |
| 100 | 100 calls to execute() |
| 1000 | 1000 calls to execute() |
Pattern observation: The total work grows directly with the number of tests.
Time Complexity: O(n)
This means if you double the number of tests, the total time to run them roughly doubles.
[X] Wrong: "Running more tests doesn't affect total time much because each test is small."
[OK] Correct: Even if each test is quick, running many tests adds up, so total time grows with the number of tests.
Understanding how test time grows helps you write efficient tests and shows you can think about code quality and maintenance.
"What if each test case itself runs a loop over data of size m? How would the time complexity change?"