Tcl: fastest way to check for existence of array element
For a specific element of an array, by far the fastest way to check is to use info exists ::myArray($myKey)
; it compiles to its own bytecode opcode (existArrayStk
) that is implemented efficiently — possibly one hash table lookup to find the array implementation (there are caches that might apply), and one hash table lookup to get the element, if any. (It's sometimes faster to not qualify the array name; that depends on context though.)
The array names
command is always going to be slower; if nothing else, it isn't bytecoded. While in this case it might be able to avoid a linear scan of the array, it's still definitely got to do list construction and so on. There's simply more costs on that code path, and likely to always be so.