Module parameters and run-time efficiency

jhidding
Tue, 17 Sep 2024 14:25:29 +0000
Performance

Hi, I want to perform dispatch based on functions of the same name within a module. There’s two ways to go about it: having a function f(m::Module,...) or defining a trait type and saying f(::Type{Mod{M}}, ...) where M.

module A
   foo(bar) = bar + bar
end

module B
  foo(bar) = bar * bar
end

foo_twice(M::Module, bar) = M.foo(M.foo(bar))

or

struct Mod{M} end

foo_twice(::Type{Mod{M}}, bar) where M = M.foo(M.foo(bar))

I found that the second is much much faster than the first. But I’m wondering why. I know that modules could be considered mutable in a way, and that would mean that M.foo falls under mutable global lookup somehow? Still, I can’t shake the feeling that these implementations should be equivalent. Am I missing something?

Cheers, Johan

4 posts - 2 participants