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.

Where Next?

Popular in Discussions Top

mmmrrr
Just saw that dhh announced https://hotwire.dev/ Is it just me or is this essentially live view? :smiley: Although I like the “iFrame-e...
New
crispinb
On reading dhh’s latest The One Person Framework it strikes me that Phoenix with LiveView is already pretty much this. However, never hav...
New
AstonJ
I’ve just started the Phoenix part of the utterly brilliant online course by @pragdave. On generating the Phoenix app he uses the --no-ec...
New
marciol
Please, let me know if this kind of discussion already took place in another topic . Hi all, how do you consider if is better to build ...
New
sergio
There’s a new TIOBE index report that came out that shows Elixir is still not in the top 50 used languages. It also goes on to call Elix...
New
rower687
Hi all, I’ve been reading a lot about the “let it crash” term and how supervising processes and the whole messaging passing make an elixi...
New
rms.mrcs
A couple of days ago I was discussing with a friend about different approaches to write microservices. He said that if he was going to w...
New
joeerl
I’m playing with Elixir - It’s fun. I think @rvirding does give Elixir courses these days. Re: files and database - when I given Erlang ...
New
paulanthonywilson
I like Umbrella projects and pretty much always use them for personal Elixir stuff, especially Nerves things. But I don’t think this is ...
New
Markusxmr
Since Drab has been developed for a while in the open, introducing the Liveview functionality in a way it happend appears to undermine th...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

We're in Beta

About us Mission Statement