5

What is the fastest way to check if an entire array is zero? For my case the elements of the array are either 1 or 0 but for reference purposes the general case can also be considered.

3 Answers3

14

LinearAlgebra`Private`ZeroArrayQ seems to do quite a good job. Curiously enough, Statistics`Library`ConstantVectorQ[#] && #[[1]] == 0 & tends to be a little bit faster on my machine.

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
4

I tested the methods from Henrik and got the following timings

linAlgZeroArrayQ = LinearAlgebra`Private`ZeroArrayQ;
statZeroArrayQ = 
  Statistics`Library`ConstantVectorQ[#] && #[[1]] == 0 &;
totalZeroArrayQ = Total[#] == 0 &;

n = 10^5; exactZeros = ConstantArray[0, n]; numericalZeros = ConstantArray[0., n]; exactSparse = exactZeros; exactSparse[[n/2]] = 1; numericalSparse = numericalZeros; numericalSparse[[n/2]] = 1.; exactRandom = RandomChoice[{0, 1}, n]; numericalRandom = RandomChoice[{0., 1.}, n];

functions = {linAlgZeroArrayQ, statZeroArrayQ, totalZeroArrayQ}; tests = {exactZeros, numericalZeros, exactSparse, numericalSparse, exactRandom, numericalRandom}; results = Table[ AbsoluteTiming[Do[functions[[j]]@tests[[i]], {10000}]][[1]], {i, 1, Length@tests}, {j, 1, Length@functions} ];

TableForm[results, TableHeadings -> {{"Exact zeros", "Numerical zeros", "Exact sparse", "Numerical sparse", "Exact random", "Numerical random"}, {"Linear Algebra method", "Statistics method", "Total"}}]

enter image description here

For the cases I tested the LinearAlgebra`Private`ZeroArrayQ seems like a clear winner but there might be cases/machines where Statistics`Library`ConstantVectorQ[#] && #[[1]] == 0 & wins.

2

You can try the following

AA = {{0, 0}, {0, 0}};
AllTrue[Flatten[AA], PossibleZeroQ]