From 9991f39c9a4fa22a221aab0bbf9e08ca7f967fa9 Mon Sep 17 00:00:00 2001 From: Lucaskyy Date: Thu, 31 Mar 2022 22:45:22 +0200 Subject: [PATCH] perf: optimize indexOf call away --- .../app/revanced/patcher/cache/Cache.kt | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/main/kotlin/app/revanced/patcher/cache/Cache.kt b/src/main/kotlin/app/revanced/patcher/cache/Cache.kt index d907cb34..33a05476 100644 --- a/src/main/kotlin/app/revanced/patcher/cache/Cache.kt +++ b/src/main/kotlin/app/revanced/patcher/cache/Cache.kt @@ -19,14 +19,13 @@ class Cache( */ fun findClass(predicate: (ClassDef) -> Boolean): ClassProxy? { // if we already proxied the class matching the predicate, - val proxiedClass = classProxy.singleOrNull { classProxy -> predicate(classProxy.immutableClass) } + val proxiedClass = classProxy.find { predicate(it.immutableClass) } // return that proxy if (proxiedClass != null) return proxiedClass // else search the original class list - val foundClass = classes.singleOrNull(predicate) ?: return null + val (foundClass, index) = classes.findIndexed(predicate) ?: return null // create a class proxy with the index of the class in the classes list - // TODO: There might be a more elegant way to the comment above - val classProxy = ClassProxy(foundClass, classes.indexOf(foundClass)) + val classProxy = ClassProxy(foundClass, index) // add it to the cache and this.classProxy.add(classProxy) // return the proxy class @@ -40,4 +39,22 @@ class MethodMap : LinkedHashMap() { } } -class MethodNotFoundException(s: String) : Exception(s) +internal class MethodNotFoundException(s: String) : Exception(s) + +internal inline fun Iterable.find(predicate: (T) -> Boolean): T? { + for (element in this) { + if (predicate(element)) { + return element + } + } + return null +} + +internal inline fun Iterable.findIndexed(predicate: (T) -> Boolean): Pair? { + for ((index, element) in this.withIndex()) { + if (predicate(element)) { + return element to index + } + } + return null +}