将 C int 数组重置为零:最快的方法? [英] Reset C int array to zero : the fastest way?

查看:36
本文介绍了将 C int 数组重置为零:最快的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个 T myarray[100],其中 T = int、unsigned int、long long int 或 unsigned long long int,那么将其所有内容重置为零的最快方法是什么(不仅用于初始化,而且在我的程序中多次重置内容)?也许使用 memset?

Assuming that we have a T myarray[100] with T = int, unsigned int, long long int or unsigned long long int, what is the fastest way to reset all its content to zero (not only for initialization but to reset the content several times in my program)? Maybe with memset?

对于像 T *myarray = new T[100] 这样的动态数组也有同样的问题.

Same question for a dynamic array like T *myarray = new T[100].

推荐答案

memset(来自 )可能是最快的标准方式,因为它是通常是直接用汇编编写并手工优化的例程.

memset (from <string.h>) is probably the fastest standard way, since it's usually a routine written directly in assembly and optimized by hand.

memset(myarray, 0, sizeof(myarray)); // for automatically-allocated arrays
memset(myarray, 0, N*sizeof(*myarray)); // for heap-allocated arrays, where N is the number of elements

<小时>

顺便说一句,在 C++ 中,惯用的方法是使用 std::fill(来自 ):

std::fill(myarray, myarray+N, 0);

哪些可以被自动优化为memset;我很确定对于 int s,它的运行速度与 memset 一样快,而如果优化器不够智能,它对于较小的类型的性能可能会稍差一些.尽管如此,如有疑问,请提供个人资料.

which may be optimized automatically into a memset; I'm quite sure that it will work as fast as memset for ints, while it may perform slightly worse for smaller types if the optimizer isn't smart enough. Still, when in doubt, profile.

这篇关于将 C int 数组重置为零:最快的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆