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

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

问题描述

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

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(来自<string.h>)可能是最快的标准方法,因为它通常是直接用汇编语言编写并手动优化的例程.

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(来自<algorithm>):


By the way, in C++ the idiomatic way would be to use std::fill (from <algorithm>):

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

可以将 自动优化为memset;我非常确定它对于int的运行速度与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天全站免登陆