From 3be613ced83379a83539156cd620da688cf6c626 Mon Sep 17 00:00:00 2001 From: Abduqodiri Qurbonzoda Date: Fri, 2 Jun 2023 16:48:00 +0300 Subject: [PATCH] [K/N] Use iterator in AbstractMutableList.indexOf/lastIndexOf Instead of access by index. To avoid performance issues when the subclass `get(index)` has non-constant time complexity. It also aligns behavior with JVM. --- .../kotlin/collections/AbstractMutableList.kt | 18 ++---------------- .../kotlin/collections/AbstractMutableList.kt | 18 ++---------------- 2 files changed, 4 insertions(+), 32 deletions(-) diff --git a/libraries/stdlib/js/src/kotlin/collections/AbstractMutableList.kt b/libraries/stdlib/js/src/kotlin/collections/AbstractMutableList.kt index 1eba0a24ace..dfbbca8fd17 100644 --- a/libraries/stdlib/js/src/kotlin/collections/AbstractMutableList.kt +++ b/libraries/stdlib/js/src/kotlin/collections/AbstractMutableList.kt @@ -67,23 +67,9 @@ public actual abstract class AbstractMutableList protected actual constructor actual override fun contains(element: E): Boolean = indexOf(element) >= 0 - actual override fun indexOf(element: E): Int { - for (index in 0..lastIndex) { - if (get(index) == element) { - return index - } - } - return -1 - } + actual override fun indexOf(element: E): Int = indexOfFirst { it == element } - actual override fun lastIndexOf(element: E): Int { - for (index in lastIndex downTo 0) { - if (get(index) == element) { - return index - } - } - return -1 - } + actual override fun lastIndexOf(element: E): Int = indexOfLast { it == element } actual override fun listIterator(): MutableListIterator = listIterator(0) actual override fun listIterator(index: Int): MutableListIterator = ListIteratorImpl(index) diff --git a/libraries/stdlib/native-wasm/src/kotlin/collections/AbstractMutableList.kt b/libraries/stdlib/native-wasm/src/kotlin/collections/AbstractMutableList.kt index 4d85e16b6cc..e1d0dc2525e 100644 --- a/libraries/stdlib/native-wasm/src/kotlin/collections/AbstractMutableList.kt +++ b/libraries/stdlib/native-wasm/src/kotlin/collections/AbstractMutableList.kt @@ -58,23 +58,9 @@ public actual abstract class AbstractMutableList protected actual constructor override actual fun contains(element: E): Boolean = indexOf(element) >= 0 - override actual fun indexOf(element: E): Int { - for (index in 0..lastIndex) { - if (get(index) == element) { - return index - } - } - return -1 - } + override actual fun indexOf(element: E): Int = indexOfFirst { it == element } - override actual fun lastIndexOf(element: E): Int { - for (index in lastIndex downTo 0) { - if (get(index) == element) { - return index - } - } - return -1 - } + override actual fun lastIndexOf(element: E): Int = indexOfLast { it == element } override actual fun listIterator(): MutableListIterator = listIterator(0) override actual fun listIterator(index: Int): MutableListIterator = ListIteratorImpl(index)