Arial wrote:
Hi,
Say you have an Int32[] with 8 elements. What is the 'best' ie:
fastest and most effiicent way to check if all elements are zero?
Thanks, Matt.
Interesting question
I suggest this:
bool IsAllZero(int[] list)
{
sum=0
foreach(int i in list) sum+=i;
return sum==0;
}
Add all values in array in sum and check if sum is zero.
From the machine code point of view that should be much faster
than checking each value with if
or sorting as someone suggested.
Do your own performance tests and let us know the results.
Happy coding!
Arial
IsAllZero(new[] {-1,1}) => true : which is wrong
bool IsAllZero(int[] list)
{
int sum=0;
foreach(int i in list) sum |= i;
return sum==0;
}
Tnx. for code patching

Your version works even for negatives, positives mix

The question remains, is there a faster way?