Selaa lähdekoodia

Improve performance

Him188 5 vuotta sitten
vanhempi
sitoutus
c89e2a7aa6

+ 15 - 4
mirai-core/src/commonMain/kotlin/net.mamoe.mirai/utils/LockFreeLinkedList.kt

@@ -51,15 +51,26 @@ fun <E> LockFreeLinkedList<E>.toMutableSet(): MutableSet<E> {
 /**
  * Builds a [Sequence] containing all the elements in [this] in the same order.
  *
- * Note that the sequence is dynamic, that is, elements are yielded atomically only when it is required
+ * Note that the sequence is dynamic
  */
 @MiraiInternalAPI
 fun <E> LockFreeLinkedList<E>.asSequence(): Sequence<E> {
-    return sequence {
-        forEach {
-            yield(it)
+    return generateSequence(head) { current: LockFreeLinkedListNode<E> ->
+        current.nextValidNode(until = tail).takeIf { it != tail }
+    }.drop(1) // drop head, should be dropped lazily
+        .map { it.nodeValue }
+}
+
+@OptIn(MiraiInternalAPI::class)
+internal fun <E> LockFreeLinkedListNode<E>.nextValidNode(until: LockFreeLinkedListNode<E>): LockFreeLinkedListNode<E> {
+    var node: LockFreeLinkedListNode<E> = this.nextNode
+    while (node != until) {
+        if (node.isValidElementNode()) {
+            return node
         }
+        node = node.nextNode
     }
+    return node
 }
 
 @MiraiInternalAPI

+ 2 - 1
mirai-core/src/jvmTest/kotlin/net/mamoe/mirai/utils/LockFreeLinkedListTest.kt

@@ -20,6 +20,7 @@ import kotlin.test.assertFalse
 import kotlin.test.assertTrue
 
 @Suppress("UnusedEquals")
+@OptIn(MiraiInternalAPI::class)
 @MiraiExperimentalAPI
 internal class LockFreeLinkedListTest {
     @Test
@@ -263,7 +264,7 @@ internal class LockFreeLinkedListTest {
      */
 }
 
-@OptIn(ExperimentalCoroutinesApi::class)
+@OptIn(ExperimentalCoroutinesApi::class, MiraiInternalAPI::class)
 @MiraiExperimentalAPI
 internal suspend inline fun <E : LockFreeLinkedList<*>> E.concurrentDo(
     numberOfCoroutines: Int,