For those of you wanting to write code that will perform well on different
AbstractArray types, starting with julia 0.4 it will be recommended that you
should typically write
for i in eachindex(A)
# do something with i and/or A[i]
end
rather than
for i = 1:length(A)
# do something with i and/or A[i]
end
The syntax
for a in A
# do something with a
end
is unchanged.
If you're using julia 0.3, the Compat package (starting with version 0.4.1)
defines `eachindex(A) = 1:length(A)`, so if you're willing to use Compat you
can already start using this syntax.
This will make a difference, in julia 0.4, when indexing arrays for which a
single linear index is inefficient---in such cases, `i` will be a
multidimensional index object. You can still say `A[i]`, and it will likely be
several times faster than if `i` were an integer. In contrast, if `A` is an
array for which linear indexing is fast, then `eachindex(A) = 1:length(A)` as
previously.
You can read more about this in the documentation for multidimensional arrays
in julia 0.4:
http://docs.julialang.org/en/latest/manual/arrays/
This public service announcement has been sponsored by the Department of
Arrays and Array Indexing.
Best,
--Tim