Skip to content

Commit 3560873

Browse files
elizarovqwwdfsad
authored andcommitted
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 e5f8412 commit 3560873

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)) {
@@ -333,18 +326,24 @@ internal class SelectBuilderImpl<in R>(
333326
}
334327
}
335328

336-
override val isSelected: Boolean get() = state !== this
329+
override val isSelected: Boolean get() = _state.loop { state ->
330+
when {
331+
state === this -> return false
332+
state is OpDescriptor -> state.perform(this) // help
333+
else -> return true // already selected
334+
}
335+
}
337336

338337
override fun disposeOnSelect(handle: DisposableHandle) {
339338
val node = DisposeNode(handle)
340-
while (true) { // lock-free loop on state
341-
val state = this.state
342-
if (state === this) {
343-
if (addLastIf(node) { this.state === this })
339+
_state.loop { state -> // lock-free loop on state
340+
when {
341+
state === this -> if (addLastIf(node) { this._state.value === this }) return
342+
state is OpDescriptor -> state.perform(this) // help
343+
else -> { // already selected
344+
handle.dispose()
344345
return
345-
} else { // already selected
346-
handle.dispose()
347-
return
346+
}
348347
}
349348
}
350349
}

0 commit comments

Comments
 (0)