When Should One Use (...)
or [...]
for Array Comprehensions?
What is the difference between the 2?
From Slack:
julia> @btime [x^2 for x in 1:10000];
6.519 μs (2 allocations: 78.20 KiB)julia> @btime (x^2 for x in 1:10000);
0.015 ns (0 allocations: 0 bytes)julia> @btime sum([x^2 for x in 1:10000]);
8.855 μs (2 allocations: 78.20 KiB)julia> @btime sum((x^2 for x in 1:10000));
1.409 ns (0 allocations: 0 bytes)julia> @btime sum(x^2 for x in 1:10000);
1.410 ns (0 allocations: 0 bytes)
The code above was by @kimlaberinto.
Some answers were:
(x^2 for x in 1:10000)
is just producing a generator.
The difference is that
()
is lazy while[]
is eager. If you perform a reduction (likesum(x^2 for x in 1:10000)
), you won’t allocate anything.
Someone also mentioned one is heap allocated while the other is stack allocated.
Please add more information on the subject.
P. S.
I’m putting it here for knowledge preservation of a discussion I read (Not participated) on Slack.