Fastest way to zero out a 2d array in C?

前端 未结 12 1487
后悔当初
后悔当初 2021-01-29 18:58

I want to repeatedly zero a large 2d array in C. This is what I do at the moment:

// Array of size n * m, where n may not equal m
for(j = 0; j < n; j++)
{
            


        
12条回答
  •  天命终不由人
    2021-01-29 19:20

    Well, the fastest way to do it is to not do it at all.

    Sounds odd I know, here's some pseudocode:

    int array [][];
    bool array_is_empty;
    
    
    void ClearArray ()
    {
       array_is_empty = true;
    }
    
    int ReadValue (int x, int y)
    {
       return array_is_empty ? 0 : array [x][y];
    }
    
    void SetValue (int x, int y, int value)
    {
       if (array_is_empty)
       {
          memset (array, 0, number of byte the array uses);
          array_is_empty = false;
       }
       array [x][y] = value;
    }
    

    Actually, it's still clearing the array, but only when something is being written to the array. This isn't a big advantage here. However, if the 2D array was implemented using, say, a quad tree (not a dynamic one mind), or a collection of rows of data, then you can localise the effect of the boolean flag, but you'd need more flags. In the quad tree just set the empty flag for the root node, in the array of rows just set the flag for each row.

    Which leads to the question "why do you want to repeatedly zero a large 2d array"? What is the array used for? Is there a way to change the code so that the array doesn't need zeroing?

    For example, if you had:

    clear array
    for each set of data
      for each element in data set
        array += element 
    

    that is, use it for an accumulation buffer, then changing it like this would improve the performance no end:

     for set 0 and set 1
       for each element in each set
         array = element1 + element2
    
     for remaining data sets
       for each element in data set
         array += element 
    

    This doesn't require the array to be cleared but still works. And that will be far faster than clearing the array. Like I said, the fastest way is to not do it in the first place.

提交回复
热议问题