# Fastest way to check if array is zero

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.

• You could use Total? Oct 13, 2020 at 13:31
• Maybe LinearAlgebraPrivateZeroArrayQ? I recall that we had a similar question not long ago... Oct 13, 2020 at 13:40
• Ah, here it is. Not a duplicate but related and thus maybe of interest: mathematica.stackexchange.com/q/230971 Oct 13, 2020 at 13:46
• @Q.P. - Total@matrix returns a vector rather than a scalar. Even if you Flatten the matrix first, you would also need to use Abs to ensure that a zero result indicated that the matrix was all zeroes. Oct 13, 2020 at 13:52
• @Q.P. Total would work but I'm interested in speed. It might be the fastest but I don't know. Oct 13, 2020 at 18:53

LinearAlgebraPrivateZeroArrayQ seems to do quite a good job. Curiously enough, StatisticsLibraryConstantVectorQ[#] && #[[1]] == 0 & tends to be a little bit faster on my machine.

I tested the methods from Henrik and got the following timings

linAlgZeroArrayQ = LinearAlgebraPrivateZeroArrayQ;
statZeroArrayQ =
StatisticsLibraryConstantVectorQ[#] && #[[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"}}]


For the cases I tested the LinearAlgebraPrivateZeroArrayQ seems like a clear winner but there might be cases/machines where StatisticsLibraryConstantVectorQ[#] && #[[1]] == 0 & wins.

You can try the following

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