I am running a code which is diagonalizing very large matrices, hence I need to reach the best possible performance. when scanning a vector I was using the following syntax
for i in 1:length(vec)
which works fine. However, I am recently receiving the following warning
Indexing with indices obtained from length, size etc is discouraged. Use eachindex or axes instead.
Is it just a good practice? or the performance is also affected?
Using eachindex ensures that your code can work with arrays that do not necessarily start with index 1. These types of arrays can be created using OffsetArrays.jl.
Yeah, I see it the other way, I normally either need the indices or just the items, if I need something together with the items itâs probably a counter.
(Plus, pairs is so obscure a name I didnât dare recommending it without double checking)
I would say (as a mnemotechnic) that pairs is for pairs of (key, value) , here (index,value), while, clearly, enumerate goes from one to the end, so is for a counter.
By the way, for enumerate it is easy to test for the first iteration ( i == 1), but how to test with last iteration ? ( does ( i == end) works? I do not see how it could). Possibly it is no a real worry, because less frequently interesting that test for first iter, but it arises sometime nevertheless.
On the other side with pairs you can do ( i == firstindex(v) ) and ( i == lastindex(v) ), even if it is somewhat verbose?
If vec is meant to a traditional (1-indexed) vector, then the âgeneralityâ argument should be weighed against the simplicity/portability of length().
I believe this trade-off is a bit different for package developers and end-users (especially newcomers to Julia).
Absolutely, but there are plenty of reasonable things pairs(vec) could have meant. I donât know what I would have wanted it to be called, I just know that I never feel entire certain what pairs does (or more likely what itâs called).
eachindex is fine and even for (i, item) in enumerate(vec) is something that most of us can handle (although it isnât pretty).
The real problem starts when dealing with matrices (and more). Things like for t = 4:T;i =2:N;x[t,i] = x[t-3,i-1];... are very easy in traditional notation, but become rather involved when you want to handle OffsetArrays (and what not). I believe this might become a serious hurdle in trying to attract new users.