Fast way to Implement a Loop

Hello, I am beginning to use Julia and I want to ask for help doing something efficiently.

I am trying to compute a summation in Julia using the following loop.

 for (k_j,kk) = enumerate(k)
       for (s_j,ss) = enumerate(s), (z_j,zz) = enumerate(z), (w_j,ww) = enumerate(w)

Which is basically calling over specific entries of matrices and adding them up. I’ve tried to make this faster and leaner with a reduce or mapreduce, but haven’t been able to get the code off the ground.

Any suggestion is appreciated, Thanks

Please provide a self-contained working example, which includes the variants you have tried and the way you are benchmarking them.


There are two things that come to my mind:

  1. Wrap your code in a function to allow precompilation and specialization on the types
    (Just pass everything the function needs as arguments - not access global variables)
  2. then write value = 0.0 to make sure that your operation is type stable ( Otherwise it is first initialized as an Int and then converted to a Float64

If you would like more specific help, you would need to provide a (minimal) working self contained example,
so that we can just copy your code and it runs.

If you post a question in several fora, please provide a link to the other question:


Just to be clear here — the “fast” way to write a for loop is to write the three letters for …. There’s no magic. There’s no need to contort things to vectorize into a mapreduce (or some other) function call. Those functions you call? They just use a Julia for loop spelled with exactly the same three letters you write.

Julia’s for loops are fast, particularly if you follow the guidance here:

1 Like