Iterating on Tuple allocates memory if values don't have identical types

Hi,
Could someone help me understand why iterating on a tuple seems much slower if the values have non-unique types?

Here is a very simple example:

a = 1.
b = [1.]
c = [1.]
A = (a, b)
B = (b, c)
@btime for d=$A; d; end
@btime for d=$B; d; end

returns:

16.892 ns (1 allocation: 32 bytes)
1.471 ns (0 allocations: 0 bytes)

Should I set up the iteration differently?

Thank you very much
Jean

First of all, welcome to our community! :confetti_ball:

Second, because the code will be inherently type unstable? The most relevant performance tip is probably: Performance Tips · The Julia Language

If you gonna go this way (what is really kinda strange to me for real code), probably the best you can do is to apply the same function (that does the same as the body of the loop) to each element separately.

3 Likes

Tuple de-structuring and indexing still work

@btime let (x,y)=$A; (x,y); end
@btime begin ($A[1],$A[2]); end

yielding

  2.200 ns (0 allocations: 0 bytes)
  2.400 ns (0 allocations: 0 bytes)
1 Like

You can also try foreach (or map if you need the result):

julia> @btime foreach(identity, $A)
  1.453 ns (0 allocations: 0 bytes)

julia> @btime map(identity, $A)
  2.585 ns (0 allocations: 0 bytes)
(1.0, [1.0])
4 Likes

Thank you for the warm welcome and the replies. Type instability is indeed the reason, now I get it.
The alternative syntaxes are also very welcome, thank you!