Does adding a dummy guard `when true` affect performance

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.

18 Likes