From 7097fb660d2f0b34e9fe9e91dcfe1be3cf0512cc Mon Sep 17 00:00:00 2001 From: preciz Date: Sat, 18 Apr 2026 00:32:03 +0200 Subject: [PATCH] Refactor: Optimize type matching in Selector using binary_part Replace complex bitstring pattern matching for namespace type matching with a 0-allocation binary_part/3 implementation. This approach avoids extracting substrings at runtime, simplifying the code, improving execution speed, and reducing memory allocation. --- lib/floki/selector.ex | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/lib/floki/selector.ex b/lib/floki/selector.ex index 8daaacdd..82e3bd43 100644 --- a/lib/floki/selector.ex +++ b/lib/floki/selector.ex @@ -120,17 +120,13 @@ defmodule Floki.Selector do ^type -> true - type_maybe_with_namespace when byte_size(type_maybe_with_namespace) > byte_size(type) -> - expected_namespace_size = byte_size(type_maybe_with_namespace) - byte_size(type) - 1 - - Kernel.match?( - << - _ns::binary-size(^expected_namespace_size), - ":", - ^type::binary - >>, - type_maybe_with_namespace - ) + type_maybe when is_binary(type_maybe) -> + type_size = byte_size(type) + node_size = byte_size(type_maybe) + + node_size > type_size and + binary_part(type_maybe, node_size - type_size - 1, 1) == ":" and + binary_part(type_maybe, node_size - type_size, type_size) == type _ -> false