travisf

travisf

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? Top

Trending in Discussions Top

budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
axelson
Hi there! :wave: @frigidcode and I (but mostly him) have been running an Elixir Book club, we’re almost done with Designing Elixir Syste...
New
achempion
I’ve been using Emacs as my main code editor for more than a two years. It’s a custom build version although I’ve tried doom emacs and sp...
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New
jtormey
Lately I’ve been thinking about how to organize components as a LiveView application grows. One of the pain points I’ve found (for myself...
New
Null-logic-0
What IDE or editor are you using for Elixir development? Personally, I use Zed, and I really like it, but sometimes I wish there were a ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews