mercredi 2 décembre 2020

Why are switch cases so much slower than else if statements in Fish?

I wrote a fish function that returned each files/subdirectory of a directory with a corresponding icon.

https://cdn.discordapp.com/attachments/752253510795526175/783515933011869696/unknown.png

I had a bash function which does the exact same thing but written with elif statement.

lsi () {
  echo "   .. "
  if [[ "$1" != "" ]]; then
    echo "$1 here"
  fi
  ls $( echo $SHOW_HIDDEN | sed 's/true/-A/' | sed 's/false//') | while read entry; do
    if [ -d "(pwd)/$entry" ]; then
      echo "   $entry"
    elif [[ $entry =~ \.(sh|c)$ ]]; then
      echo "   $entry"
    elif [[ $entry =~ \.(md|txt|log)$|rc$ ]]; then
      echo "   $entry"
    elif [[ $entry =~ \.(jpg|png|svg|webp)$ ]]; then
      echo "   $entry"
    elif [[ $entry =~ \.fish$ ]]; then
      echo "   $entry"
    elif [[ $entry =~ \.py$ ]]; then
      echo "   $entry"
    elif [[ $entry =~ \.js$ ]]; then
      echo "   $entry"
    elif [[ $entry =~ \.mp4|mkv$ ]]; then
      echo "辶   $entry"
    elif [[ $entry =~ \.(mp3|m4a)$ ]]; then
      echo "   $entry"
    elif [[ $entry =~ \.(pdf)$ ]]; then
      echo "   $entry"
    elif [[ $entry =~ \.(tar|zip) ]]; then
      echo "遲    $entry"
    else
      echo "   $entry"
    fi
  done
}

When I did some testing in larger directories like /usr/bin or even Pictures, the bash script was noticeably faster especialy on usr/bin.

I rewrote the fish with else if statement

function lsi --description "ls with icons"
  echo "   .. "
  if $SHOW_HIDDEN
    set all -A
  end
  if ! test -z $argv[1]
    echo $argv[1]
  end
  for entry in (ls $all)
    if test -d "$entry"
      echo "   $entry"
    else if string match -rq '\.sh$' $entry
      echo "   $entry"
    else if string match -rq '\.(md|txt|log)|rc$' $entry
      echo "   $entry"
    else if string match -rq '\.(jpg|png|svg|webp|gif)$' $entry
      echo "   $entry"
    else if string match -rq '\.fish$' $entry
      echo "   $entry"
    else if string match -rq '\.rs$' $entry
      echo "   $entry"
    else if string match -rq '\.(c|h)$' $entry
      echo "   $entry"
    else if string match -rq '\.py$' $entry
      echo "   $entry"
    else if string match -rq '\.js$' $entry
      echo "   $entry"
    else if string match -rq '\.go$' $entry
      echo "   $entry"
    else if string match -rq '\.pdf$' $entry
      echo "   $entry"
    else if string match -rq '\.(mp4|mkv)$' $entry
      echo "辶   $entry"
    else if string match -rq '\.(tar|zip)$' $entry
      echo "遲    $entry"
    else
      echo "   $entry"
    end
  end
end

and now they perform almost identically.

I'd like to know why the switch case version is so much slower. Is it because the fish built in is bad or does it has something to do the switch cases in general?

Aucun commentaire:

Enregistrer un commentaire