3 ms·
Not knowing the internals of Array#size implementation / Array data structure, but my first thought would be whether Array#empty? could just check for the prese
by themgt 9y ago
Not knowing the internals of Array#size implementation / Array data structure, but my first thought would be whether Array#empty? could just check for the presence of at least one element (i.e. stop at the first), rather than checking whether the size of a large array is equal to zero.
- nirvdrum 9y agoWhile there's no requirement that a Ruby Array is implemented as an array in the implementation language (C, C++, Java, etc.), in practice it is in all the Ruby implementations. In order to traverse an array, you need to know the length so you can ensure your array index is in bounds. I.e., to read the first element of an array, you'll need to read the size anyway. That being the case, you would want to compare the size to 0 because comparing ints is much faster than reading from memory.