Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

accessing array by index very slow



$ zsh -c 'a=($(seq 1000000)); time (for ((i=0;i<10000;i++)) { : "${a[1]}"; })'
( for ((i=0; i<10000; i++)) do; : "${a[1]}"; done; )  0.07s user 0.03s system 96% cpu 0.102 total

$ zsh -c 'a=($(seq 1000000)); time (for ((i=0;i<10000;i++)) { : "${a[999999]}"; })'
( for ((i=0; i<10000; i++)) do; : "${a[999999]}"; done; )  14.56s user 0.06s system 99% cpu 14.616 total

Accessing array elements via their index is very slow,
especially for large index values.

Comparing with other shells:

~$ bash -c 'a=($(seq 1000000)); time (for ((i=0;i<10000;i++)) { : "${a[999999]}"; })'

real    0m0.078s
user    0m0.077s
sys     0m0.000s
~$ ksh -c 'a=($(seq 1000000)); time (for ((i=0;i<10000;i++)) { : "${a[999999]}"; })'

real    0m00.02s
user    0m00.02s
sys     0m00.00s

cachegrind reveals the time is spent in arrlen_ge(), as zsh
needs to walk through the whole array to determine whether
999999 is past the end of the array or not.

Why doesn't zsh record the length of arrays to avoid that
gymnastic (and speed up $#array expansion)?

-- 
Stephane




Messages sorted by: Reverse Date, Date, Thread, Author