[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: let vs double-parentheses
From: |
Lawrence Velázquez |
Subject: |
Re: let vs double-parentheses |
Date: |
Sat, 6 Mar 2021 21:23:46 -0500 |
> On Mar 6, 2021, at 8:28 PM, Peng Yu <pengyu.ut@gmail.com> wrote:
>
>> - For another example, when one wants to process arguments as
>> arithmetic expressions, one may write something like `let "$@"' using
>> let. If one wants to do it with `((...))', one needs to combine it
>> with a for loop as `for expr; do ((expr)); done'.
>>
>> - For a more practical example, when one wants to calculate
>> 1+2+3+....+100, one can write `let a=0 a+={1..100}' using let, but
>> need to write `a=0; for ((i=1;i<100;i++)); do ((a+=i)); done' using
>> `((...))'.
>
> Thanks for the info.
>
> Performance-wise, it seems that "let" may be better in certain cases.
> I was not aware of this syntax `a+={1..100000}`.
It's just normal brace expansion.
bash-5.1$ echo let a=0 a+={1..5}
let a=0 a+=1 a+=2 a+=3 a+=4 a+=5
> Is there any other
> syntax that could have better performance as well?
>
> $ time let a=0 a+={1..100000}
>
> real 0m0.306s
> user 0m0.295s
> sys 0m0.009s
> $ time { a=0; for ((i=1;i<=100000;i++)); do ((a+=i)); done; }
>
> real 0m0.611s
> user 0m0.607s
> sys 0m0.001s
This particular trick of syntax is not very compelling, as the
closed-form expression is simple.
bash-5.1$ time (( r=1, s=100000, a=(s-r+1)*(r+s)/2 ))
real 0m0.000s
user 0m0.000s
sys 0m0.000s
vq