Skip to content

Replace Bitwise xor with :crypto.exor#8

Merged
josevalim merged 1 commit into
elixir-plug:masterfrom
denvaar:use-erlang-crypto-exor-for-mask
Feb 9, 2020
Merged

Replace Bitwise xor with :crypto.exor#8
josevalim merged 1 commit into
elixir-plug:masterfrom
denvaar:use-erlang-crypto-exor-for-mask

Conversation

@denvaar

@denvaar denvaar commented Feb 9, 2020

Copy link
Copy Markdown
Contributor

No description provided.

@josevalim

Copy link
Copy Markdown
Member

Hi @denvaar! Have you benchmarked both approaches? A 40 bytes long binary is a reasonable payload to benchmark with. Thanks!

@denvaar

denvaar commented Feb 9, 2020

Copy link
Copy Markdown
Contributor Author

Here are some results. The difference is quite small, but there is a difference (0.17 μs/op vs 3.11 μs/op) I'm not sure if there are other factors to consider.

iex(1)> input_a = :crypto.strong_rand_bytes(40)
<<11, 71, 42, 174, 69, 99, 233, 48, 182, 46, 122, 189, 246, 94, 59, 227, 217,
  214, 188, 40, 81, 131, 219, 32, 83, 155, 39, 58, 183, 121, 10, 22, 132, 148,
  100, 107, 249, 145, 197, 125>>
iex(2)> input_b = :crypto.strong_rand_bytes(40)
<<223, 157, 121, 169, 104, 218, 32, 1, 97, 157, 49, 2, 47, 165, 18, 13, 148,
  182, 133, 121, 238, 176, 203, 53, 84, 157, 0, 72, 134, 237, 8, 241, 242, 221,
  64, 110, 103, 200, 135, 183>>
iex(3)> Benchwarmer.benchmark [&:crypto.exor/2, &MaskTest.mask/2], [input_a, input_b]
*** &:crypto.exor/2 ***
1.3 sec     8M iterations   0.17 μs/op

*** &MaskTest.mask/2 ***
1.6 sec   524K iterations   3.11 μs/op

Where MaskTest.mask/2 is

defmodule MaskTest do
  use Bitwise

  def mask(left, right) do
    mask(left, right, "")
  end

  defp mask(<<x, left::binary>>, <<y, right::binary>>, acc) do
    mask(left, right, <<acc::binary, x ^^^ y>>)
  end

  defp mask(<<>>, <<>>, acc) do
    acc
  end
end

@josevalim
josevalim merged commit fb60cfd into elixir-plug:master Feb 9, 2020
@josevalim

Copy link
Copy Markdown
Member

💚 💙 💜 💛 ❤️

@denvaar
denvaar deleted the use-erlang-crypto-exor-for-mask branch February 9, 2020 14:37
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