https://kotlinlang.org logo
Title
e

Exerosis

02/24/2022, 3:20 PM
What kind of overhead is involved in marking functions as suspending when you don't have any suspension points? For example if I have a special data structure called Mutable<Key, Value> and it has get(Key) and set(Key, Value) right now those are not suspending functions... but sometimes I need to make a data structure that wraps a database or does some other costly operation. If I changed the whole definition to suspend fun get(Key) etc. I would pretty much need to mark every function in my whole framework suspend. Other than the fact that from a readability/usability standpoint that sucks, how much would I be crippling myself by doing that? Would it make more sense to just wait on java's project loom and use that instead/along side kotlin coroutines?
c

Casey Brooks

02/24/2022, 3:25 PM
It won't cost much in terms of runtime performance (even coroutines that do have suspension points are very cheap, it's the threading itself that is costly). The compiler adds an extra parameter to the function, but that would be about it. In terms of usability, yeah making everything suspend would be pretty cumbersome. Maybe having 2 separate classes (one suspending, one normal) might be better
e

ephemient

02/24/2022, 3:34 PM
if your function has no suspend points (or only has a suspending tail call), the compiler doesn't even generate a state machine for it, so the generated code won't cost any more than a non-suspending function
e

Exerosis

02/24/2022, 9:15 PM
Ah really? But it does still have a Continuation param right? Also is it still the case that only one Continuation object is created for the whole chain of suspending calls (starting at the base like, launch/runBlocking call)? the problem is that even if I have two classes, to access the suspending one in most places would mean making a bunch of other abstractions suspend, so pretty much everything becomes suspend if anything is.
e

ephemient

02/24/2022, 10:05 PM
yes it still has a hidden continuation parameter. but basically this should come down to your intended API and not performance. IMO if you expect to need suspension within your library, then you should do the work now to plumb suspension through your API, because it's easier to remove suspend later on than it is to add it