Updated 2014-07-16 00:10:32 by AMG

array size arrayName

Returns a decimal string giving the number of elements in the array. If arrayName isn't the name of an array then 0 is returned.

Subcommand of array, returns the number of keys in the array given by name. Example:
 % array set arr {foo 1 bar 2 grill 3}
 % array size arr
 3

It has been pointed out in the Tcl chatroom that array size is almost double as slow as array statistics which returns much more data (try it to see..) If the speed matters, replace calls to [array size arrayName] with [lindex [array statistics arrayName] 0]

DKF: However, please note that [array statistics] is not guaranteed to return the right answer. See this (trimmed) transcript for why:
 % array set foo {a a b b c c d d e e}
 % array stat foo
 5 entries in table, 4 buckets
 [...]
 average search distance for entry: 1.2
 % # Demonstrate the case that everyone thinks of first...
 % unset foo(b)
 % array stat foo
 4 entries in table, 4 buckets
 [...]
 average search distance for entry: 1.3
 % set foo(b) b
 b
 % array stat foo
 5 entries in table, 4 buckets
 [...]
 average search distance for entry: 1.2
 % # Now demonstrate the nasty case which makes things fall apart...
 % upvar 0 foo(b) b
 % unset b
 % array stat foo
 5 entries in table, 4 buckets
 [...]
 average search distance for entry: 1.2
 % array size foo
 4

MGS [2003/09/24] - With 8.4.4, I find [array size arrayName] to be the quickest, with [llength [array names arrayName]] about two to three times as slow, and [lindex [array statistics arrayName] 0] about ten times as slow.

See also: