Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize stub_with #157

Merged
merged 2 commits into from
Jun 22, 2024
Merged

Conversation

ypconstante
Copy link
Contributor

Today stub_with calls stub for each functions that needs to be stubbed. This causes a significant overhead because some validations being done repeatedly, and sending multiple messages to store the state change.

This PR updates stub_with to avoid the issues above by storing a list with the stub key and expectation, and sending a single state update.

Name                   ips        average  deviation         median         99th %
bench (PR)         33.02 K       30.28 μs    ±25.30%       28.40 μs       65.52 μs
bench (main)        2.88 K      347.63 μs     ±9.18%      339.18 μs      453.12 μs

Comparison: 
bench (PR)         33.02 K
bench (main)        2.88 K - 11.48x slower +317.34 μs

Memory usage statistics:

Name                 average  deviation         median         99th %
bench (PR)           7.53 KB     ±0.15%        7.53 KB        7.53 KB
bench (main)        55.34 KB     ±0.10%       55.36 KB       55.36 KB

Comparison: 
bench (PR)           7.53 KB
bench (main)        55.34 KB - 7.35x memory usage +47.81 KB
defmodule BenchBehaviour do
  @functions Enum.map(1..50, &:"get_v#{&1}")

  for function <- @functions do
    @callback unquote(function)() :: integer()
  end
end

defmodule BenchBehaviourImpl do
  @behaviour BenchBehaviour

  @functions Enum.map(1..50, &:"get_v#{&1}")

  for function <- @functions do
    @impl BenchBehaviour
    def unquote(function)() do
      unquote(function)
    end
  end
end

Mox.defmock(BenchBehaviourMock, for: BenchBehaviour)

Benchee.run(
  %{
    "bench" => fn ->
      Mox.stub_with(BenchBehaviourMock, BenchBehaviourImpl)
      NimbleOwnership.cleanup_owner({:global, Mox.Server}, self())
    end
  },
  time: 10,
  memory_time: 2
)

@josevalim josevalim merged commit 2b67d0a into dashbitco:main Jun 22, 2024
2 checks passed
@josevalim
Copy link
Member

💚 💙 💜 💛 ❤️

@ypconstante ypconstante deleted the optimize-stub_with branch June 22, 2024 13:48
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