简体   繁体   English

清除char数组最佳方案 - memset与否?

[英]Clearing out a char array best scenario - memset or not?

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); 在进入无限循环然后使用memset(buff, 0, 60); )之前,声明char buff(将包含包含换行符和换行符的字符串memset(buff, 0, 60); or 要么
  2. Keeping it the way it is. 保持原样。 Does memset affect performance ? memset会影响性能吗?

Note: 注意:

My requirement is that I need to have the char array totally clean everytime the loop restarts. 我的要求是每次循环重启时我都需要将char数组完全清理干净。

"The way it is" doesn't give you an array full of zeros. “它的方式”不会给你一个充满零的数组。 But you don't have to call memset anyway. 但是你无论如何都不必调用memset 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: 如果你只是在循环内部使用buff ,我认为最好将它保持在循环的范围内:

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

memset does some work, so it must "affect performance". memset做了一些工作,所以它必须“影响性能”。 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: 如果您一直将其用作C样式字符串:

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. 这只会设置第一个字节,但如果您将它用作简单的C样式字符串,那么您需要设置它以使其成为零长度字符串。 It is faster than any solution that fills the entire buffer by probably a factor of 7 on a 64-bit machine. 在64位计算机上,它比任何填充整个缓冲区的解决方案要快7倍。

If you actually need the entire buffer filled with 0, then 如果你确实需要填充0的整个缓冲区,那么

char buff[60] = {}; char buff [60] = {};

will do that. 会这样做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM