is memset() more efficient than for loop in C?

前端 未结 7 1395
不思量自难忘°
不思量自难忘° 2021-02-02 06:46

is memset more efficient than for loop. so if i have

char x[500];
memset(x,0,sizeof(x));

or

char x[500];
for(int i = 0 ; i &         


        
相关标签:
7条回答
  • 2021-02-02 07:11
    void fill_array(void* array, size_t size_of_item, size_t length, void* value) {
      uint8_t* bytes      = value;
      uint8_t  first_byte = bytes[0];
    
      if (size_of_item == 1) {
        memset(array, first_byte, length);
        return;
      }
    
      // size_of_item > 1 here.
      bool all_bytes_are_identical = true;
    
      for (size_t byte_index = 1; byte_index < size_of_item; byte_index++) {
        if (bytes[byte_index] != first_byte) {
          all_bytes_are_identical = false;
          break;
        }
      }
    
      if (all_bytes_are_identical) {
        memset(array, first_byte, size_of_item * length);
        return;
      }
    
      for (size_t index = 0; index < length; index++) {
        memcpy((uint8_t*)array + size_of_item * index, value, size_of_item);
      }
    }
    

    memset is more efficient, it shouldn't care about non symmetric values (where all_bytes_are_identical is false). So you will search how to wrap it.

    This is my variant. It is working for both little and big endian systems.

    0 讨论(0)
提交回复
热议问题