Delay vs Thread.sleep in Kotlin - Performance Comparison
We want to understand how waiting methods affect program execution time.
How does using delay or Thread.sleep change the time a program takes?
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 the loops, recursion, array traversals that repeat.
- Primary operation: The wait call inside the loop (
delayorThread.sleep). - How many times: Exactly
ntimes, once per loop iteration.
Each wait adds a fixed time, so total time grows directly with n.
| Input Size (n) | Approx. Operations (Waits) |
|---|---|
| 10 | 10 waits x 100ms = 1 second |
| 100 | 100 waits x 100ms = 10 seconds |
| 1000 | 1000 waits x 100ms = 100 seconds |
Pattern observation: The total wait time increases steadily as n grows.
Time Complexity: O(n)
This means the total time grows in a straight line as the number of waits increases.
[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.
Understanding how waiting affects program time helps you write efficient and responsive code, a skill valued in many programming tasks.
What if we changed the wait time inside the loop from 100ms to 1 second? How would the time complexity change?