Discussion:
[Help-bash] Can `declare -i` increase the performance of integer arithmetic?
Peng Yu
2018-01-21 19:10:31 UTC
Permalink
Hi,

I tried `declare -i`. But it doesn't see to improve performance. Is it
supposed to improve the performance? Thanks.

$ time ./script2.sh; time ./script.sh

real 0m6.764s
user 0m6.733s
sys 0m0.015s

real 0m6.810s
user 0m6.782s
sys 0m0.010s

==> script.sh <==
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

declare -i i
for ((i=0;i<1000000;++i))
do
:
done

==> script2.sh <==
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

for ((i=0;i<1000000;++i))
do
:
done
--
Regards,
Peng
Eduardo Bustamante
2018-01-22 05:18:43 UTC
Permalink
Post by Peng Yu
Hi,
I tried `declare -i`. But it doesn't see to improve performance. Is it
supposed to improve the performance? Thanks.
No, it's not meant to improve performance.
Peng Yu
2018-01-22 13:48:57 UTC
Permalink
Post by Eduardo Bustamante
No, it's not meant to improve performance.
Then, what is the purpose of `declare -i`?
--
Regards,
Peng
Pierre Gaston
2018-01-22 14:28:24 UTC
Permalink
Post by Peng Yu
Post by Eduardo Bustamante
No, it's not meant to improve performance.
Then, what is the purpose of `declare -i`?
--
Regards,
Peng
It can save you a couple of $(( )):

declare -i sum
sum=2+3
echo $sum # prints 5
sum+=1
echo $sum # prints 6
Chet Ramey
2018-01-22 14:28:52 UTC
Permalink
Post by Peng Yu
Post by Eduardo Bustamante
No, it's not meant to improve performance.
Then, what is the purpose of `declare -i`?
The purpose is as documented.

For assignment statements:

"If the variable has its integer attribute set, then value
is evaluated as an arithmetic expression even if the $((...)) expansion
is not used (see Arithmetic Expansion below)."

This has implications for how += is treated when applied to a variable
with the integer attribute set.
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU ***@case.edu http://tiswww.cwru.edu/~chet/
Chet Ramey
2018-02-08 16:27:21 UTC
Permalink
Is a variable always stored as a string whether `declare -i` is used?
Yes.
It sounds like if `declare -i` is used on a variable, it is content
should be saved as an integer instead of a string as it is likely that
subsequent arithmetic operations will be performed on the variable. Is
it?
No.
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU ***@case.edu http://tiswww.cwru.edu/~chet/
Loading...