Skip to content

Optimize EEx fn block detection - #15738

Merged
josevalim merged 1 commit into
elixir-lang:mainfrom
preciz:optimize-eex-fn-block-scan
Aug 12, 2026
Merged

Optimize EEx fn block detection#15738
josevalim merged 1 commit into
elixir-lang:mainfrom
preciz:optimize-eex-fn-block-scan

Conversation

@preciz

@preciz preciz commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Assisted-by: Codex CLI:GPT-5.6 Sol

Scan reversed tokens once to identify whether a stab expression starts an anonymous function block.

Bench:

Mix.install([{:benchee, "~> 1.3"}])

defmodule FnBlockBench do
  def old(tokens) do
    fn_index = Enum.find_index(tokens, &match?({:fn, _}, &1)) || :infinity
    end_index = Enum.find_index(tokens, &match?({:end, _}, &1)) || :infinity
    end_index > fn_index
  end

  def new([{:fn, _} | _]), do: true
  def new([{:end, _} | _]), do: false
  def new([_ | tokens]), do: new(tokens)
  def new([]), do: false
end

token = {:identifier, {1, 1, nil}, :value}

inputs =
  Map.new([10, 100, 1_000], fn size ->
    {"#{size} preceding tokens", [token, {:fn, {1, 1, nil}} | List.duplicate(token, size)]}
  end)

Benchee.run(
  %{"old" => &FnBlockBench.old/1, "new" => &FnBlockBench.new/1},
  inputs: inputs,
  time: 2,
  warmup: 1
)
   Preceding tokens          New          Old    Difference
  ━━━━━━━━━━━━━━━━━━  ━━━━━━━━━━━  ━━━━━━━━━━━  ━━━━━━━━━━━━
                 10     28.47 ns    135.09 ns         4.75×
  ──────────────────  ───────────  ───────────  ────────────
                100     27.01 ns    719.61 ns        26.64×
  ──────────────────  ───────────  ───────────  ────────────
              1,000    0.0308 μs      6.62 μs       215.23×

Scan reversed tokens once to identify whether a stab expression starts an anonymous function block.

Assisted-by: Codex:GPT-5
@josevalim
josevalim merged commit 9158e33 into elixir-lang:main Aug 12, 2026
15 checks passed
@josevalim

Copy link
Copy Markdown
Member

💚 💙 💜 💛 ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants