在清洁和速度方面的动态与静态记忆的最佳实践 [英] Best practices of dynamic vs. static memory in terms of cleanliness and speed

查看:93
本文介绍了在清洁和速度方面的动态与静态记忆的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,称为x,其大小为6 * sizeof(float)。我知道,声明:

I have an array, called x, whose size is 6*sizeof(float). I'm aware that declaring:

float x[6];

会为堆栈内存中的x分配6 * sizeof(float)。但是,如果我执行以下操作:

would allocate 6*sizeof(float) for x in the stack memory. However, if I do the following:

float *x;   // in class definition

x = new float[6];   // in class constructor

delete [] x;    // in class destructor



我会将6 * sizeof(float)的动态内存分配给x。如果x的大小在类的生命周期不变,在清洁和速度的最佳实践方面(我不清楚地回忆,如果不正确,堆栈内存操作比动态内存操作更快),我应该确保那x是静态而不是动态分配的内存?提前感谢。

I would be allocating dynamic memory of 6*sizeof(float) to x. If the size of x does not change for the lifetime of the class, in terms of best practices for cleanliness and speed (I do vaguely recall, if not correctly, that stack memory operations are faster than dynamic memory operations), should I make sure that x is statically rather than dynamically allocated memory? Thanks in advance.

推荐答案

声明固定大小的数组肯定会更快。每个单独的动态分配需要找到一个未占用的块,这不是很快。

Declaring the array of fixed size will surely be faster. Each separate dynamic allocation requires finding an unoccupied block and that's not very fast.

因此,如果你真的关心速度(已剖析),规则是如果你不需要动态分配 - 不要使用它。如果你需要它 - 考虑两倍分配多少,因为重新分配不是很快。

So if you really care about speed (have profiled) the rule is if you don't need dynamic allocation - don't use it. If you need it - think twice on how much to allocate since reallocating is not very fast too.

这篇关于在清洁和速度方面的动态与静态记忆的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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