0
0
Kotlinprogramming~5 mins

Delay vs Thread.sleep in Kotlin - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Delay vs Thread.sleep
O(n)
Understanding Time Complexity

We want to understand how waiting methods affect program execution time.

How does using delay or Thread.sleep change the time a program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


suspend fun waitWithDelay(n: Int) {
    repeat(n) {
        kotlinx.coroutines.delay(100L) // non-blocking wait
    }
}

fun waitWithSleep(n: Int) {
    repeat(n) {
        Thread.sleep(100L) // blocking wait
    }
}
    

This code repeats a wait operation n times using either delay or Thread.sleep.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The wait call inside the loop (delay or Thread.sleep).
  • How many times: Exactly n times, once per loop iteration.
How Execution Grows With Input

Each wait adds a fixed time, so total time grows directly with n.

Input Size (n)Approx. Operations (Waits)
1010 waits x 100ms = 1 second
100100 waits x 100ms = 10 seconds
10001000 waits x 100ms = 100 seconds

Pattern observation: The total wait time increases steadily as n grows.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows in a straight line as the number of waits increases.

Common Mistake

[X] Wrong: "Using delay is faster because it doesn't block the thread."

[OK] Correct: Both delay and Thread.sleep cause the program to wait the same total time; delay just lets other tasks run meanwhile, but the total wait still grows with n.

Interview Connect

Understanding how waiting affects program time helps you write efficient and responsive code, a skill valued in many programming tasks.

Self-Check

What if we changed the wait time inside the loop from 100ms to 1 second? How would the time complexity change?