Ah, yes, this seems to have fixed the problem, thank you. Now, when not in global scope, using eachindex is definitely the fastest approach. I made some measurements over 1000 runs for each of the approaches in the original post, here are the averages: Using eachindex: 0.0026683 Using ranges: 0.0041256 Using in: 0.0031200
I guess I'll stick with eachindex. :) On Thursday, February 25, 2016 at 1:50:04 PM UTC, Stefan Karpinski wrote: > > Can you try it not in global scope? > > On Thu, Feb 25, 2016 at 5:17 AM, abc <a.sto...@gmail.com <javascript:>> > wrote: > >> For the following matrix >> my_matrix = randn(10000, 1000) >> using eachindex to access all elements is much slower than using ranges >> or even for el in my_matrix, even though it says in the documentation ( >> http://docs.julialang.org/en/release-0.4/stdlib/arrays/#Base.eachindex) >> that eachindex uses ranges for Arrays. >> >> Some code and numbers: >> julia> sum = 0.0 >> julia> @time for iter in eachindex(my_matrix) >> sum += my_matrix[iter] >> end >> 1.288944 seconds (50.00 M allocations: 915.519 MB, 3.36% gc time) >> julia> sum = 0.0 >> julia> @time for i in 1:10000, j in 1:1000 >> sum += my_matrix[i,j] >> end >> 0.681678 seconds (34.38 M allocations: 524.582 MB, 2.45% gc time) >> julia> sum = 0.0 >> julia> @time for el in my_matrix >> sum += el >> end >> 1.063564 seconds (40.00 M allocations: 762.993 MB, 3.41% gc time) >> >> Am I reading the documentation wrong, or is there something strange with >> the matrix indexing? Because as it is, I don't see any benefit of using >> anything different than simple ranges for manipulating matrices. >> > >