質問

In my current code I have something like this

while(true) //Infinite loop
{
   char buff[60];
   .....
   ....
}

I wanted to know what would be better performance wise.

  1. Declaring the char buff (that will hold strings that contain linefeeds and new line character) before entering the infinite loop and then using memset(buff, 0, 60); or
  2. Keeping it the way it is. Does memset affect performance ?

Note:

My requirement is that I need to have the char array totally clean everytime the loop restarts.

役に立ちましたか?

解決

"The way it is" doesn't give you an array full of zeros. But you don't have to call memset anyway. If you are only to use buff inside of the loop, I think it is better to keep it in the scope of the loop:

while(true) //Infinite loop
{
   char buff[60] = {}; // buff is full of zeros
   .....
   ....
}

他のヒント

memset does some work, so it must "affect performance". It's generally heavily optimized though, because it's a common operation.

You're unlikely to find a faster way to clear the array because of this, and for comparison the code you showed does not initialize the array at all.

For reference, it should probably look like:

char buff[60];
while (true) {
    memset(buff, 0, sizeof(buff));
    ...

The only solution likely to be faster is finding a way to stop depending on the buffer being zeroed at the start of each iteration

If you are consistently using it as a C style string:

char buff[60];
buff[0] = 0;   

This will only set the first byte, but if you are using it as a simple C style string, that is all you ever need to set to make it a zero-length string. It is faster than any solution that fills the entire buffer by probably a factor of 7 on a 64-bit machine.

If you actually need the entire buffer filled with 0, then

char buff[60] = {};

will do that.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top