Skip to content

Optimize JSON map key encoding - #15824

Merged
josevalim merged 1 commit into
elixir-lang:mainfrom
preciz:inline-key-in-json
Sep 1, 2026
Merged

Optimize JSON map key encoding#15824
josevalim merged 1 commit into
elixir-lang:mainfrom
preciz:inline-key-in-json

Conversation

@preciz

@preciz preciz commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Assisted-by: Codex CLI:GPT-5.6 Sol

Inline the per-key dispatch to avoid a private function call for every encoded map entry.

Bench:

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

inputs =
  for key_type <- [:binary, :atom, :integer], size <- [10, 100, 1000], into: %{} do
    entries =
      Enum.map(1..size, fn index ->
        key =
          case key_type do
            :binary -> "key#{index}"
            :atom -> String.to_atom("key#{index}")
            :integer -> index
          end

        {key, index}
      end)

    {"#{key_type} keys (#{size})", Map.new(entries)}
  end

Benchee.run(
  %{"JSON.encode_to_iodata!/1" => &JSON.encode_to_iodata!/1},
  inputs: inputs,
  warmup: 2,
  time: 5,
  reduction_time: 2
)

Results:

  - Base: 7bd7665a9
  - Current: 36e700b08
  - OTP 29, JIT enabled, one scheduler
  - Each cell is the mean of Benchee’s reported average across three runs

   Input                      Base      Current    Faster
  ━━━━━━━━━━━━━━━━━━━━  ━━━━━━━━━━━  ━━━━━━━━━━━  ━━━━━━━━
   Atom keys ×10         546.80 ns    491.81 ns    10.06%
  ────────────────────  ───────────  ───────────  ────────
   Atom keys ×100         6.057 µs     5.363 µs    11.45%
  ────────────────────  ───────────  ───────────  ────────
   Atom keys ×1000       72.263 µs    62.560 µs    13.43%
  ────────────────────  ───────────  ───────────  ────────
   Binary keys ×10       488.05 ns    442.15 ns     9.40%
  ────────────────────  ───────────  ───────────  ────────
   Binary keys ×100       5.340 µs     4.560 µs    14.61%
  ────────────────────  ───────────  ───────────  ────────
   Binary keys ×1000     61.090 µs    52.720 µs    13.70%
  ────────────────────  ───────────  ───────────  ────────
   Integer keys ×10      696.37 ns    655.10 ns     5.93%
  ────────────────────  ───────────  ───────────  ────────
   Integer keys ×100      7.363 µs     6.603 µs    10.32%
  ────────────────────  ───────────  ───────────  ────────
   Integer keys ×1000    81.840 µs    73.710 µs     9.93%

  Geometric-mean improvement across all nine inputs: 11.02%

Inline the per-key dispatch to avoid a private function call for every encoded map entry.

Assisted-by: Codex:GPT-5
@josevalim
josevalim merged commit a229c0e into elixir-lang:main Sep 1, 2026
13 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