lud
Does adding a dummy guard `when true` affect performance
In order to only have one branch of code in a macro that defines functions with support for guards, I would like to always have a guard.
So I want to define the generated functions as def myfun(arg1,arg2) when true do when no guard is given.
I suspect that the compiler will get rid of it and that it will not impact performance, but I am not sure how to verify that.
Thank you.
Marked As Solved
al2o3cr
You can use the :S option to @compile to cause Elixir to dump a text representation of the generated bytecode.
For this module (in foo.ex):
defmodule Foo do
@compile :S
def without_guard(x) do
x + 1
end
def with_guard(x) when true do
x + 1
end
end
Compiling it with elixir foo.ex produces a CompileError - that’s expected, because the @compile :S has caused the compiler to stop midway. The relevant bit of the result in foo.ex.S:
{function, with_guard, 1, 11}.
{label,10}.
{line,[{location,"foo.ex",8}]}.
{func_info,{atom,'Elixir.Foo'},{atom,with_guard},1}.
{label,11}.
{line,[{location,"foo.ex",9}]}.
{gc_bif,'+',{f,0},1,[{x,0},{integer,1}],{x,0}}.
return.
{function, without_guard, 1, 13}.
{label,12}.
{line,[{location,"foo.ex",4}]}.
{func_info,{atom,'Elixir.Foo'},{atom,without_guard},1}.
{label,13}.
{line,[{location,"foo.ex",5}]}.
{gc_bif,'+',{f,0},1,[{x,0},{integer,1}],{x,0}}.
return.
Other than labels and line numbers, with_guard and without_guard produce identical bytecode.
Also Liked
harrisi
I’ll also add that, in my experience, adding guards tends to increase performance, not decrease. In some cases it can be a significant speed increase.
Always crucial to profile actual code, though!







