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?
Practice
delay and Thread.sleep in Kotlin?Solution
Step 1: Understand
delaybehaviordelaysuspends the coroutine but does not block the underlying thread, allowing other coroutines to run.Step 2: Understand
Thread.sleepbehaviorThread.sleepblocks the entire thread, stopping all work on that thread until the sleep time ends.Final Answer:
delaypauses a coroutine without blocking the thread, whileThread.sleepblocks the thread. -> Option BQuick Check:
delay = non-blocking pause, Thread.sleep = blocking pause [OK]
- Thinking delay blocks the thread
- Confusing coroutine suspension with thread blocking
- Assuming both behave the same way
delay in a Kotlin coroutine?Solution
Step 1: Recall
delaysyntaxdelayis a suspend function called with the time in milliseconds as an argument, e.g.,delay(1000).Step 2: Identify incorrect options
Thread.delayanddelay.sleepdo not exist.Thread.sleepis a different blocking function.Final Answer:
delay(1000) -> Option DQuick Check:
Correct syntax for delay = delay(1000) [OK]
- Using Thread.delay instead of delay
- Confusing delay with Thread.sleep syntax
- Calling delay outside coroutine scope
import kotlinx.coroutines.*
fun main() = runBlocking {
println("Start")
delay(500)
println("Middle")
Thread.sleep(500)
println("End")
}Solution
Step 1: Analyze the coroutine flow
The program prints "Start", then suspends for 500ms usingdelay, then prints "Middle".Step 2: Analyze the thread blocking
After "Middle",Thread.sleep(500)blocks the thread for 500ms, then prints "End".Final Answer:
Start Middle End (with 1 second total delay) -> Option AQuick Check:
delay + Thread.sleep = total 1 second pause [OK]
- Assuming delay and Thread.sleep run in parallel
- Thinking delay blocks the thread
- Confusing output order
import kotlinx.coroutines.*
fun main() = runBlocking {
println("Before sleep")
Thread.sleep(1000)
println("After sleep")
}Solution
Step 1: Identify blocking call in coroutine
Thread.sleep(1000)blocks the thread, which is not recommended inside coroutines.Step 2: Suggest coroutine-friendly alternative
Usedelay(1000)to suspend the coroutine without blocking the thread.Final Answer:
ReplaceThread.sleep(1000)withdelay(1000)to avoid blocking the thread. -> Option CQuick Check:
Use delay, not Thread.sleep, inside coroutines [OK]
- Using Thread.sleep inside coroutines
- Trying to use Thread.delay which doesn't exist
- Ignoring thread blocking effects
delay correctly to avoid blocking threads and runs tasks concurrently?
fun main() = runBlocking {
// Choose the correct code snippet
}Solution
Step 1: Understand concurrency with coroutines
Usinglaunchstarts concurrent coroutines. Inside them,delaysuspends without blocking threads.Step 2: Analyze options for concurrency and blocking
launch { delay(1000); println("Task 1 done") } launch { delay(1000); println("Task 2 done") } usesdelayinsidelaunch, enabling concurrency. launch { Thread.sleep(1000); println("Task 1 done") } launch { Thread.sleep(1000); println("Task 2 done") } blocks threads withThread.sleep. Thread.sleep(1000); println("Task 1 done") Thread.sleep(1000); println("Task 2 done") blocks main thread sequentially. delay(1000); println("Task 1 done") delay(1000); println("Task 2 done") callsdelayoutside coroutine scope, causing error.Final Answer:
launch { delay(1000); println("Task 1 done") } launch { delay(1000); println("Task 2 done") } -> Option AQuick Check:
Use launch + delay for concurrent non-blocking tasks [OK]
- Using Thread.sleep inside launch blocks threads
- Calling delay outside coroutine scope
- Running tasks sequentially blocking main thread
Ready to prove it?
Pass the test and this pattern moves unknown
