On Tue, Oct 4, 2016 at 3:11 PM, Jeff <[email protected]> wrote:
> Adding floats to an element of a vector takes about twice as long as adding
> float to a variable. For example,
>
> ```
>     val = zeros(1)
>     for i in 1:10000000
>         val[1] += 9.
>     end
> ```
> finishes in 0.034 seconds whereas
> ```
>     a = 0.
>     for i in 1:10000000
>         a += 9.
>     end
> ```
> take just 0.015 seconds.
>
> Is the former block of code looking up the address in memory of `val[1]` at
> every iteration? Or does have something to do with `a` being stack allocated
> whereas `val` is heap allocated?

It's because of bounds check.

>
> Is there a way to add floats to a particular index of a vector without
> incurring runtime overhead, if I know at compile time what the index is?

The optimizations the compiler can do is actually a little limited in
this case. But if you know that no one else will be using the same
array at the same time you can do the unsafe optimization manually by
hoisting the load and the store out of the loop.

val1 = val[1]
for ...
     val1 += 9.
end
val[1] = val1

>
> Thanks!
>

Reply via email to