Small inconsistency between generators and vectors

Just noticed, the MWE

using Random
using BenchmarkTools
Random.seed!(42)
array = rand(1_000_000)
x = @btime sum([y*y for y in $array]) 
z = @btime sum(y*y for y in $array) 
@show x
@show z
@assert z == x

yields (obviously?)

  1.810 ms (2 allocations: 7.63 MiB)
  1.006 ms (0 allocations: 0 bytes)
x = 332909.22931042255
z = 332909.2293104364
ERROR: AssertionError: z == x

so Julia doesn’t always use pairwise sum?

Edit: noticed this analyzing @TouchSir’s posting.

It isn’t possible for the generators (second) version. The generator can only be traversed linearly.
Well, in your example it is possible, as the array is already realized, but this special case is probably not considered in the code. Your example is a bit artificial, why would you create a generator over an existing array?

2 Likes