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
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
optimize_boolean is a red herring here - it marks the enclosed AST so that a later pass can expand it:
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 ![]()
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:
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_defaultuses_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_eqshows theoptimize_booleanmachinery doing its thing - it optimizes to the same instructions aswith_case_default! Since the compiler knows==cannot returnnil, 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_defaultform. -
with_case_whenandwith_if_whensupply the compiler with type information via anis_booleanguard, 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
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.
Popular in Discussions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








