Skip to content

Add binary optimization to chunk_request_body - #184

Merged
cmullaparthi merged 1 commit into
cmullaparthi:masterfrom
nickva:binary-optimize-chunk_requst_body
Apr 30, 2026
Merged

cmullaparthi merged 1 commit into
cmullaparthi:masterfrom
nickva:binary-optimize-chunk_requst_body

Conversation

@nickva

@nickva nickva commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Inspired by #74 tried running ERL_COMPILER_OPTIONS=bin_opt_info with OTP 27.

From the list the only good candidate for optimization seems to be chunk_request_body, and to get it to optimize had break out the binary case into a separate function then use a case there.

[1] https://erlang.org/documentation/doc-15.0-rc1/doc/system/binaryhandling.html

Before

rm ebin/ibrowse_http_client.beam ; ERL_COMPILER_OPTIONS=bin_opt_info make 2>&1
rm: ebin/ibrowse_http_client.beam: No such file or directory
 ERLC   ibrowse_lib.erl ibrowse.erl ibrowse_http_client.erl ibrowse_sup.erl ibrowse_app.erl ibrowse_lb.erl ibrowse_socks5.erl
compile: warnings being treated as errors
src/ibrowse_http_client.erl:1231: BINARY CREATED: binary is used in call to chunk_request_body/3 which doesn't support context reuse
% 1231|     chunk_request_body(Rest, ChunkSize, [Chunk | Acc]);

src/ibrowse_http_client.erl:1231: NOT OPTIMIZED: binary used in call to chunk_request_body/3, where binary is used in '=='/2 before being matched
% 1231|     chunk_request_body(Rest, ChunkSize, [Chunk | Acc]);

After

% rm ebin/ibrowse_http_client.beam ; ERL_COMPILER_OPTIONS=bin_opt_info make 2>&1
rm: ebin/ibrowse_http_client.beam: No such file or directory
 ERLC   ibrowse_lib.erl ibrowse.erl ibrowse_http_client.erl ibrowse_sup.erl ibrowse_app.erl ibrowse_lb.erl ibrowse_socks5.erl
compile: warnings being treated as errors
src/ibrowse_http_client.erl:1243: OPTIMIZED: match context reused
% 1243|             chunk_binary_body(Rest, ChunkSize, [Chunk | Acc]);

src/ibrowse_http_client.erl:1248: OPTIMIZED: match context reused
% 1248|             BodySize = byte_size(Body),

I don't know if we had any tests for chunk encoding so added some (such that they run in CI as well).

Inspired by cmullaparthi#74 tried running
`ERL_COMPILER_OPTIONS=bin_opt_info` with OTP 27.

From the list the only good candidate for optimization seems to be
chunk_request_body, and to get it to optimize had break out the binary case
into a separate function then use a `case` there.

[1] https://erlang.org/documentation/doc-15.0-rc1/doc/system/binaryhandling.html

Befre
```
rm ebin/ibrowse_http_client.beam ; ERL_COMPILER_OPTIONS=bin_opt_info make 2>&1
rm: ebin/ibrowse_http_client.beam: No such file or directory
 ERLC   ibrowse_lib.erl ibrowse.erl ibrowse_http_client.erl ibrowse_sup.erl ibrowse_app.erl ibrowse_lb.erl ibrowse_socks5.erl
compile: warnings being treated as errors
src/ibrowse_http_client.erl:1231: BINARY CREATED: binary is used in call to chunk_request_body/3 which doesn't support context reuse
% 1231|     chunk_request_body(Rest, ChunkSize, [Chunk | Acc]);

src/ibrowse_http_client.erl:1231: NOT OPTIMIZED: binary used in call to chunk_request_body/3, where binary is used in '=='/2 before being matched
% 1231|     chunk_request_body(Rest, ChunkSize, [Chunk | Acc]);
```

After
```
% rm ebin/ibrowse_http_client.beam ; ERL_COMPILER_OPTIONS=bin_opt_info make 2>&1
rm: ebin/ibrowse_http_client.beam: No such file or directory
 ERLC   ibrowse_lib.erl ibrowse.erl ibrowse_http_client.erl ibrowse_sup.erl ibrowse_app.erl ibrowse_lb.erl ibrowse_socks5.erl
compile: warnings being treated as errors
src/ibrowse_http_client.erl:1243: OPTIMIZED: match context reused
% 1243|             chunk_binary_body(Rest, ChunkSize, [Chunk | Acc]);

src/ibrowse_http_client.erl:1248: OPTIMIZED: match context reused
% 1248|             BodySize = byte_size(Body),
```

I don't know if we had any tests for chunk encoding so added some (such that
they run in CI as well).
@nickva

nickva commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Benchmarking this with the script below, shows 1.8x speed improvement compared to master

erl -noshell -s chunk_bench run -s erlang halt
body=10485760  chunk=4096  iters/call=2560  runs=10
old: median 1241.99 us/call  range  958.75 .. 1547.00 us
new: median  682.88 us/call  range  537.23 ..  943.27 us
speedup (median):  1.82x
%  erl -noshell -s chunk_bench run -s erlang halt

-module(chunk_bench).
-export([run/0]).

-define(BODY_SIZE, 10 * 1024 * 1024).
-define(CHUNK_SIZE, 4096).
-define(ITERS, 100).
-define(RUNS, 10).

% old chunks
old_chunk(Body, ChunkSize) ->
    old_chunk(Body, ChunkSize, []).

old_chunk(Body, _ChunkSize, Acc) when Body == <<>>; Body == [] ->
    lists:reverse(["\r\n", "0\r\n" | Acc]);
old_chunk(Body, ChunkSize, Acc) when is_binary(Body),
                                     size(Body) >= ChunkSize ->
    <<ChunkBody:ChunkSize/binary, Rest/binary>> = Body,
    Chunk = [dec2hex(ChunkSize), "\r\n", ChunkBody, "\r\n"],
    old_chunk(Rest, ChunkSize, [Chunk | Acc]);
old_chunk(Body, _ChunkSize, Acc) when is_binary(Body) ->
    BodySize = size(Body),
    Chunk = [dec2hex(BodySize), "\r\n", Body, "\r\n"],
    lists:reverse(["\r\n", "0\r\n", Chunk | Acc]).

% new chunks
new_chunk(Body, ChunkSize) ->
    new_chunk_loop(Body, ChunkSize, []).

new_chunk_loop(Body, ChunkSize, Acc) ->
    case Body of
        <<ChunkBody:ChunkSize/binary, Rest/binary>> ->
            Chunk = [dec2hex(ChunkSize), "\r\n", ChunkBody, "\r\n"],
            new_chunk_loop(Rest, ChunkSize, [Chunk | Acc]);
        <<>> ->
            lists:reverse(["\r\n", "0\r\n" | Acc]);
        _ ->
            BodySize = byte_size(Body),
            Chunk = [dec2hex(BodySize), "\r\n", Body, "\r\n"],
            lists:reverse(["\r\n", "0\r\n", Chunk | Acc])
    end.

dec2hex(N) -> integer_to_list(N, 16).

run() ->
    Body = crypto:strong_rand_bytes(?BODY_SIZE),
    OldFun = fun() -> old_chunk(Body, ?CHUNK_SIZE) end,
    NewFun = fun() -> new_chunk(Body, ?CHUNK_SIZE) end,
    % assert they are the same
    case iolist_to_binary(OldFun()) /= iolist_to_binary(NewFun()) of
        true -> exit({results_diverge, OldFun(), NewFun()});
        false -> ok
    end,
    % a bit of a warmup
    [begin OldFun(), NewFun() end || _ <- lists:seq(1, 3)],
    Seqs = lists:seq(1, ?RUNS),
    {OldTimes, NewTimes} = lists:unzip([{do_loop(OldFun), do_loop(NewFun)} || _ <- Seqs]),
    OldUs = median(OldTimes),
    NewUs = median(NewTimes),
    io:format("body=~B  chunk=~B  iters/call=~B  runs=~B~n", [?BODY_SIZE, ?CHUNK_SIZE, ?BODY_SIZE div ?CHUNK_SIZE, ?RUNS]),
    io:format("old: median ~7.2f us/call  range ~7.2f .. ~7.2f us~n", [OldUs, lists:min(OldTimes), lists:max(OldTimes)]),
    io:format("new: median ~7.2f us/call  range ~7.2f .. ~7.2f us~n", [NewUs, lists:min(NewTimes), lists:max(NewTimes)]),
    io:format("speedup (median):  ~.2fx~n", [OldUs / max(NewUs, 0.001)]),
    ok.

do_loop(Fun) ->
    erlang:garbage_collect(),
    T0 = erlang:monotonic_time(microsecond),
    loop(Fun, ?ITERS),
    T1 = erlang:monotonic_time(microsecond),
    (T1 - T0) / ?ITERS.

loop(_, 0) ->
    ok;
loop(Fun, N) ->
    Fun(),
    loop(Fun, N - 1).

median(L) ->
    Sorted = lists:sort(L),
    lists:nth((length(Sorted) + 1) div 2, Sorted).

@nickva

nickva commented Apr 30, 2026

Copy link
Copy Markdown
Contributor Author

@cmullaparthi sorry to bother again, you have a chance to take a look?

There are two other small cleanup/modernization PRs (#185 and #186). If they look good, would it be possible to have a new release tag?

@cmullaparthi
cmullaparthi merged commit 4a0743f into cmullaparthi:master Apr 30, 2026
4 checks passed
@cmullaparthi

Copy link
Copy Markdown
Owner

Thank you @nickva great work!

@nickva
nickva deleted the binary-optimize-chunk_requst_body branch May 1, 2026 03:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants