help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How case statement is tested?


From: Peng Yu
Subject: Re: How case statement is tested?
Date: Wed, 11 Mar 2020 21:17:27 -0500

>> I am wondering if there is any optimization in testing the conditions
>> in a case statement?
>
> What optimization(s) do you have in mind?  Bash has to perform
> glob-matching for each potential pattern.  Anything you can do to speed
> up globbing (such as recognizing when a glob can only match a literal
> string) might help, but since side effects are possible in specifying a
> glob pattern, there's very little you can do to parallelize things by
> testing multiple glob patterns at once.  For example:
>
> x= y=
> case 1 in
>    $((x=0)) ) ;;
>    $((y=1)) ) ;;
>    $((x=1)) ) ;;
> esac
> echo "$x.$y"
>
> must output 0.1, which means you cannot precompute the pattern for the
> third clause bounded by $((x=1)) (which is really the glob '1' plus the
> side-effect of setting x=1) until after you have already ascertained
> whether the first two clauses did not match.
>
>>
>> Or it is just like a series of if-statement and each condition must be
>> tested until one condition is true? Thanks.
>
> This, with the additional complication that you can skip conditions
> (with ';&') or evaluate more than one condition as true (with ';;&').
> See if you can figure out what this will output prior to running it:

No. I can not figure it out without running it. :)

> for var in a b c d; do
>    case $var in
>      a) echo 1 ;;&
>      b) echo 2 ;&
>      c) echo 3 ;;
>      *) echo 4
>    esac
> done

So the conclusion is that if I only use ";;" in `case` and there are
only hardcoded test patterns, a case statement is essentially the same
as a big if-elif-elif-...then statement in terms of performance?
(Basically, the conditions will be tested one after another until a
condition matches.)

Thanks.

-- 
Regards,
Peng



reply via email to

[Prev in Thread] Current Thread [Next in Thread]