travisf

travisf

When to use: Case vs if

I’m curious what the consensus (if there is one) on case vs if statements for conditionals is. Specifically, in cases where you are only dealing with boolean options for example not is_nil(value).

Personally, when I write Elixir I find that I reach for case way, way more than if even when if would work fine. I think I do it because I don’t always know all the potential conditionals when I start writing the function, I like the sort of open ended nature of case as one can add other cases over time. I also just find something visually unappealing about if statements compared to case when I read Elixir code.

I’m not totally against if I use it from time to time when I know that there will only ever be two conditions or when I can do a single line: if foo, do: func(foo), else: func(bar).

Is this an anti-pattern is there a good reason why I should start using if more regularly?

Most Liked

stefanchrobot

stefanchrobot

I think that if works great for boolean conditions and it’s often used in the Elixir’s codebase. I’d say that case with just true/false feels weird.

al2o3cr

al2o3cr

optimize_boolean is a red herring here - it marks the enclosed AST so that a later pass can expand it:

https://github.com/elixir-lang/elixir/blob/8d76faa3faf508b0f67835f9d1891aa484f9acda/lib/elixir/src/elixir_expand.erl#L688-L693

If the AST definitely has only true/false, rewrite_case_clauses replaces the when x in [false, nil] clause generated by if with… case / end with two branches :thinking:

However, I don’t think it’s directly related to your situation since returns_boolean has a very specific list of things it’s looking for:

https://github.com/elixir-lang/elixir/blob/8d76faa3faf508b0f67835f9d1891aa484f9acda/lib/elixir/src/elixir_utils.erl#L187-L225

and MapSet.member? isn’t on that.


A more interesting (IMO) thing to look at around performance is the shape of the BEAM code produced by the compiler. @compile :S is helpful as ever, given this input:

defmodule Foo2 do
  @compile :S

  def with_if(arg) do
    if arg do
      :ok
    else
      :nope
    end
  end

  def with_sim_if(arg) do
    case arg do
      false -> :nope
      nil -> :nope
      _ -> :ok
    end
  end

  def with_case(arg) do
    case arg do
      true -> :ok
      false -> :nope
    end
  end

  def with_case_default(arg) do
    case arg do
      false -> :nope
      _ -> :ok
    end
  end

  def with_if_eq(arg) do
    if arg == false do
      :nope
    else
      :ok
    end
  end

  def with_if_when(arg) when is_boolean(arg) do
    if arg do
      :ok
    else
      :nope
    end
  end

  def with_case_when(arg) when is_boolean(arg) do
    case arg do
      true -> :ok
      false -> :nope
    end
  end
end

with_if shows that the case generated by the macro translates directly to a select instruction:

  {label,17}.
    {select_val,{x,0},{f,19},{list,[{atom,false},{f,18},{atom,nil},{f,18}]}}.
  {label,18}.
    {move,{atom,nope},{x,0}}.
    return.
  {label,19}.
    {move,{atom,ok},{x,0}}.
    return.

with_sim_if produces exactly the same instructions (other than different labels for being in a different function):

  {label,20}.
    {line,[{location,"foo2.ex",12}]}.
    {func_info,{atom,'Elixir.Foo2'},{atom,with_sim_if},1}.
  {label,21}.
    {select_val,{x,0},{f,23},{list,[{atom,false},{f,22},{atom,nil},{f,22}]}}.
  {label,22}.
    {move,{atom,nope},{x,0}}.
    return.
  {label,23}.
    {move,{atom,ok},{x,0}}.
    return.

I’d expect that form to have exactly the same performance as if in your example.

The code for the case with explicit true and false is slightly different:

  {label,9}.
    {select_val,{x,0},{f,12},{list,[{atom,false},{f,11},{atom,true},{f,10}]}}.
  {label,10}.
    {move,{atom,ok},{x,0}}.
    return.
  {label,11}.
    {move,{atom,nope},{x,0}}.
    return.
  {label,12}.
    {line,[{location,"foo2.ex",21}]}.
    {case_end,{x,0}}.

This version has a third possible way to exit, if arg isn’t true or false.

I suspect this may cause the performance difference - maybe an optimization in the JIT for simple branches?

There are some other interesting variations:

  • with_case_default uses _ instead of true, so there’s no “third exit”. It produces very different instructions:

    {label,14}.
      {test,is_eq_exact,{f,15},[{x,0},{atom,false}]}.
      {move,{atom,nope},{x,0}}.
      return.
    {label,15}.
      {move,{atom,ok},{x,0}}.
      return.
    

    I suspect this is competitively fast, if not faster than others.

  • with_if_eq shows the optimize_boolean machinery doing its thing - it optimizes to the same instructions as with_case_default! Since the compiler knows == cannot return nil, that part of the check has been removed:

    {label,25}.
      {test,is_eq_exact,{f,26},[{x,0},{atom,false}]}.
      {move,{atom,nope},{x,0}}.
      return.
    {label,26}.
      {move,{atom,ok},{x,0}}.
      return.
    

    I’d expect this to perform identically to the with_case_default form.

  • with_case_when and with_if_when supply the compiler with type information via an is_boolean guard, so they both produce identical instructions:

    {label,17}.
      {select_val,{x,0},{f,16},{list,[{atom,false},{f,19},{atom,true},{f,18}]}}.
    {label,18}.
      {move,{atom,ok},{x,0}}.
      return.
    {label,19}.
      {move,{atom,nope},{x,0}}.
      return.
    
eksperimental

eksperimental

I pretty much feel the same way you do.

I think if/2 is a good fit when you have:

  • no other nested ifs under it,
  • when you check for truthy/false values.

Other than that I prefer to use case and cond. cond is particularly useful for replacing nested ifs or if/elseifs.

Last Post!

BartOtten

BartOtten

If this is the case, a case could be made for if. Exception to the rule: when the else case raises. You have to try yourself.

Where Next?

Popular in Discussions Top

CharlesO
Erlang :list.nth simple, but 1 - based nth(1, [H|_]) -> H; nth(N, [_|T]) when N > 1 -> nth(N - 1, T). Elixir Enum.at … coo...
New
pillaiindu
In django there is a cache framework backed by memcached. Rails also puts a lot of emphasis on caching, and even the idea of russian-doll...
New
nburkley
AWS re:Invent is on at the moment with some interesting announcements. One new feature in particular is the Lambda Runtime API for AWS La...
New
Fl4m3Ph03n1x
Background A few days ago I was listening to The future of Elixir from Elixir Talks, with Dave Thomas (@pragdave ) and Brian Mitchell. I...
New
cvkmohan
The upcoming Phoenix 1.6 release looks very interesting. Became a habit to watch the commits - and - what they are bringing in. phx.gen...
New
AstonJ
Can you believe the first professionally published Elixir book was published just 8 years ago? Since then I think we’ve seen more books f...
New
matthias_toepp
I’d love to hear what people think about Wisp, the new Gleam web framework started by Gleam’s primary creator Louis Pilfold. Gleam, alon...
New

Other popular topics Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54260 488
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New

We're in Beta

About us Mission Statement