zsh-workers
 help / color / mirror / code / Atom feed
From: Stephane Chazelas <stephane@chazelas.org>
To: Zsh hackers list <zsh-workers@zsh.org>
Subject: accessing array by index very slow
Date: Sun, 16 Apr 2023 10:03:42 +0100	[thread overview]
Message-ID: <20230416090342.dztvzcnzpbyukgfq@chazelas.org> (raw)

$ 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


             reply	other threads:[~2023-04-16  9:04 UTC|newest]

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2023-04-16  9:03 Stephane Chazelas [this message]
2023-04-16  9:10 ` Roman Perepelitsa
2023-04-16  9:19   ` Sebastian Gniazdowski
2023-04-16 15:27     ` Bart Schaefer
2023-04-16 22:03       ` Mikael Magnusson
2023-04-18  2:43         ` Bart Schaefer
2023-04-30 19:26           ` Bart Schaefer

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20230416090342.dztvzcnzpbyukgfq@chazelas.org \
    --to=stephane@chazelas.org \
    --cc=zsh-workers@zsh.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).