0
0
Blockchain / Solidityprogramming~5 mins

Writing test cases in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing test cases
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

Look for loops or repeated actions.

  • Primary operation: Calling execute() on each test case.
  • How many times: Once for each test in the list.
How Execution Grows With Input

As you add more tests, the total time grows in a simple way.

Input Size (n)Approx. Operations
1010 calls to execute()
100100 calls to execute()
10001000 calls to execute()

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

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of tests, the total time to run them roughly doubles.

Common Mistake

[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.

Interview Connect

Understanding how test time grows helps you write efficient tests and shows you can think about code quality and maintenance.

Self-Check

"What if each test case itself runs a loop over data of size m? How would the time complexity change?"