https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

CLOVIS

10/09/2020, 5:14 PM
I'm working on a project where the main thread should never block or even be slowed down. To ensure that any ‘expensive' calculation (everything taking ~10ms or more is too much) is never executed on the main thread, I'm thinking to add the
suspend
modifier to anything that might be expensive, even if it doesn't suspend, to ensure I don't accidentally call it on the main thread. Do you think it's a good/bad idea? Are there any performance implications of the added parameter? It's a JVM-only project, and I don't care about Java interoperability here.
l

louiscad

10/09/2020, 5:24 PM
Adding the suspend modifier doesn't prevent from calling on the main thread and yields no magic. You can however wrap possibly expensive computations with
Dispatchers.Default { }
and blocking I/O with
<http://Dispatchers.IO|Dispatchers.IO> { }
.
☝️ 3
l

Luis Munoz

10/09/2020, 7:36 PM
Maybe you can just have an assertion statement assert(Thread.current().name != "main")
c

CLOVIS

10/14/2020, 1:10 PM
@Luis Munoz but that has a runtime overhead, and cannot tell me if I forgot one somewhere during coding until I execute it
l

Luis Munoz

10/14/2020, 1:25 PM
If you are worried about a few asserts you should write your program in c. You can use the thread id instead of string also Also can't think of any other options?
My first setence is some what crud let me say instead ""Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."Donald Knuth' -
c

CLOVIS

10/14/2020, 5:45 PM
I mean, sure, but having a
suspend
keyword allows me to get compile-time verification, even if the cost is small for a runtime-only verification, I'm still going to go with the better & more performant solution?
l

louiscad

10/14/2020, 5:47 PM
@CLOVIS Verification of what? Also, has my comment above been of any help?
3 Views