git » sdk » commit d0019c2

Use existsFast

author Stephen Paul Weber
2025-06-24 17:57:23 UTC
committer Stephen Paul Weber
2025-06-24 17:57:23 UTC
parent d8d158d2c886d5d3a56830895ca52a3fc6d3edcc

Use existsFast

Profiling showed this very hot path spending a lot of time in string
equality checks it doesn't need to do because we really don't need to
use reflection here. Specializing to Array gets rid of the reflection in
the output.

snikket/Client.hx +1 -1
snikket/Util.hx +12 -0

diff --git a/snikket/Client.hx b/snikket/Client.hx
index a04c24a..42999e1 100644
--- a/snikket/Client.hx
+++ b/snikket/Client.hx
@@ -113,7 +113,7 @@ class Client extends EventEmitter {
 		});
 
 		stream.on("sm/update", (data) -> {
-			final anySyncHappening = chats.exists(chat -> chat.uiState != Closed && chat.syncing());
+			final anySyncHappening = Util.existsFast(chats, chat -> chat.uiState != Closed && chat.syncing());
 			persistence.storeStreamManagement(accountId(), anySyncHappening ? null : data.sm);
 			return EventHandled;
 		});
diff --git a/snikket/Util.hx b/snikket/Util.hx
index 15b54ba..9f293c7 100644
--- a/snikket/Util.hx
+++ b/snikket/Util.hx
@@ -16,6 +16,18 @@ function setupTrace() {
 #end
 }
 
+// Faster just by specializing to array
+inline function existsFast<A>(it:Array<A>, f:(item:A) -> Bool) {
+	var result = false;
+	for (x in it) {
+		if (f(x)) {
+			result = true;
+			break;
+		}
+	}
+	return result;
+}
+
 // Std.downcast doesn't play well with null safety
 function downcast<T, S>(value: T, c: Class<S>): Null<S> {
 	return cast Std.downcast(cast value, cast c);