Skip to content
This repository was archived by the owner on Dec 31, 2024. It is now read-only.

Commit 45ac09f

Browse files
committed
Optimise slightly the iterator
Avoid unnecessary String.length calls as these are very expensive
1 parent 2c54a4f commit 45ac09f

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

lib/text_delta/iterator.ex

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,22 +52,28 @@ defmodule TextDelta.Iterator do
5252
end
5353

5454
def next({[head_a | _], [head_b | _]} = sets, skip_type) do
55-
comparison = Operation.compare(head_a, head_b)
5655
skip = Operation.type(head_a) == skip_type
57-
do_next(sets, comparison, skip)
56+
len_a = Operation.length(head_a)
57+
len_b = Operation.length(head_b)
58+
59+
cond do
60+
len_a > len_b -> do_next(sets, :gt, len_b, skip)
61+
len_a < len_b -> do_next(sets, :lt, len_a, skip)
62+
true -> do_next(sets, :eq, 0, skip)
63+
end
5864
end
5965

60-
defp do_next({[head_a | tail_a], [head_b | tail_b]}, :gt, false) do
61-
{head_a, remainder_a} = Operation.slice(head_a, Operation.length(head_b))
66+
defp do_next({[head_a | tail_a], [head_b | tail_b]}, :gt, len, false) do
67+
{head_a, remainder_a} = Operation.slice(head_a, len)
6268
{{head_a, [remainder_a | tail_a]}, {head_b, tail_b}}
6369
end
6470

65-
defp do_next({[head_a | tail_a], [head_b | tail_b]}, :lt, _) do
66-
{head_b, remainder_b} = Operation.slice(head_b, Operation.length(head_a))
71+
defp do_next({[head_a | tail_a], [head_b | tail_b]}, :lt, len, _) do
72+
{head_b, remainder_b} = Operation.slice(head_b, len)
6773
{{head_a, tail_a}, {head_b, [remainder_b | tail_b]}}
6874
end
6975

70-
defp do_next({[head_a | tail_a], [head_b | tail_b]}, _, _) do
76+
defp do_next({[head_a | tail_a], [head_b | tail_b]}, _, _, _) do
7177
{{head_a, tail_a}, {head_b, tail_b}}
7278
end
7379
end

0 commit comments

Comments
 (0)