开发者

Optimal Code for initialization

Which of the following code would be optimal for initializing array?

char szCommand[2048] ={0}

char s开发者_高级运维zCommand[2048];
memset(szCommand,0,2048);


The second is not initializing the array, it's more like assigning to it. I think if ever there would be any noticeable difference (there won't be) you'd have to profile it yourself and see that the first version might be a tiiiiiny bit faster - but that's only when the optimizations are off. Premature optimization is the root of all evil - just DON"T think about it


The performance difference between the two versions would be so insignificant (if the compiler doesn't optimize away the difference) that I'd be inclined to go with the most readable one.


For null terminated strings, in my opinion, the optimal initialization is this

szCommand[0] = 0;


Any decent compiler should emit the same code for both cases. In the case of memset, the compiler can eliminate the function call by understanding the semantics of the functions from the standard library.


Both are same, first version is compact - that's it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜