I’m trying to understand the interaction between array views and Boolean indexing.
In general, my understanding (and experience thus far) is that views generally increasing performance when you’re not modifying the array slices. For example:
x = collect(1:1000) @btime z = x[50:200]; 107.278 ns (1 allocation: 1.33 KiB) @btime z = @view x[50:200]; 19.084 ns (1 allocation: 48 bytes)
However, now do the equivalent operations using Boolean indexing, and the performance is reversed:
w = (x .>= 50) .& (x .<= 200); @btime z = $x[$w]; 167.926 ns (3 allocations: 1.38 KiB) @btime z = @view $x[$w]; 210.821 ns (6 allocations: 1.45 KiB)
Interesting. So I go to the Julia manual to read more about logical indexing. The manual states:
Indexing by a boolean vector
Bis effectively the same as indexing by the vector of integers that is returned by
findall(B)…It is generally more efficient to use boolean arrays as indices directly instead of first calling
Let’s see how explicitly calling
findall affects performance:
@btime z = $x[findall($w)]; 286.378 ns (3 allocations: 2.67 KiB) : @btime z = @view $x[findall($w)]; 174.572 ns (4 allocations: 1.41 KiB)
The extra function call decreases performance in the first case (as expected), but actually increases performance when using
So that I know when to use @view in my own code, I’m trying to wrap my head around what’s going here. Is this just a corner case where @view is not performing well because it hasn’t been optimized for logical indexing? Is there anyway to get the combined performance of logical indexing and views simultaneously? Is there a deeper insight here I should be absorbing about how views work?