I consistently get heap allocations in groups of 3 of 4.33 KiB for each chain of comparisons:
x = randn(Float64, (2,3)) y = similar(x) z @btime @. $y = -1 <= $x < 1
This prints “481.026 ns (3 allocations: 4.33 KiB)”.
This seems to be a property of how chained comparisons are handled in Julia (similar to how view allocates a SubArray of 64 bytes) since the number and size of allocations always appears to be the same despite the size of the array itself. Chaining onto the same chain doesn’t change this; however, multiple chains separated by logical operators each allocate the same way: 3 allocations of 4.33 KiB.
There are currently two workarounds I’ve identified: not using chained comparisons by separating each comparison with an & operator or looping over the array such that each chained comparison is done on scalar values. I would prefer not having to resort to either since they compromise readability and conciseness in my opinion. Additionally this has a massive impact within for loops as 4.33 KiB is comparable to storing a double precision array of 554 elements. Looping a vectorized chained comparison statement just 1024 times will allocate 4.33 GiB. Is there a better way to do this?