Skip to content

Commit 0c96b0b

Browse files
committed
Small performance optimizations of select instance impl
Get rid of private state-reading helper that does "is OpDescriptor" instance check and rearrange the code so that we don't have to do this check on the fast path.
1 parent d994b66 commit 0c96b0b

File tree

1 file changed

+14
-15
lines changed
  • kotlinx-coroutines-core/common/src/selects

1 file changed

+14
-15
lines changed

kotlinx-coroutines-core/common/src/selects/Select.kt

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -308,13 +308,6 @@ internal class SelectBuilderImpl<in R>(
308308
override fun toString(): String = "SelectOnCancelling[${this@SelectBuilderImpl}]"
309309
}
310310

311-
private val state: Any? get() {
312-
_state.loop { state ->
313-
if (state !is OpDescriptor) return state
314-
state.perform(this)
315-
}
316-
}
317-
318311
@PublishedApi
319312
internal fun handleBuilderException(e: Throwable) {
320313
if (trySelect(null)) {
@@ -326,18 +319,24 @@ internal class SelectBuilderImpl<in R>(
326319
}
327320
}
328321

329-
override val isSelected: Boolean get() = state !== this
322+
override val isSelected: Boolean get() = _state.loop { state ->
323+
when {
324+
state === this -> return false
325+
state is OpDescriptor -> state.perform(this) // help
326+
else -> return true // already selected
327+
}
328+
}
330329

331330
override fun disposeOnSelect(handle: DisposableHandle) {
332331
val node = DisposeNode(handle)
333-
while (true) { // lock-free loop on state
334-
val state = this.state
335-
if (state === this) {
336-
if (addLastIf(node) { this.state === this })
332+
_state.loop { state -> // lock-free loop on state
333+
when {
334+
state === this -> if (addLastIf(node) { this._state.value === this }) return
335+
state is OpDescriptor -> state.perform(this) // help
336+
else -> { // already selected
337+
handle.dispose()
337338
return
338-
} else { // already selected
339-
handle.dispose()
340-
return
339+
}
341340
}
342341
}
343342
}

0 commit comments

Comments
 (0)