memory - 在什么情况下静态分配比动态分配好?

标签 memory memory-management

我正在经历做出的一些决定 Xara Xtreme ,一个开源的 SVG 图形应用程序。他们的内存管理决策对我来说非常有趣,因为我天真地认为按需动态分配是编写面向对象应用程序的方式。

文档中的解释是

How on earth can static allocations be efficient?

If you are used to large dynamic data structures, this may seem strange to you. Firstly, all our objects (and thus allocation size) are far smaller (on average) than each dynamic area allocation within a program such as Impression. This means that though there are likely to be many holes within memory, they are small. Also, we have far more allocated objects within memory, and thus these holes quickly get filled. Furthermore, virtual memory managers will free up any pages of memory that contain no allocations and give this memory back to the operating system so that it may be used again (either by us, or by another task).

We benefit greatly from the fact that whenever we allocate memory in this manner, we do not have to move any memory about. This proved a bottleneck in ArtWorks which also had many small allocations being used concurrently. more



简而言之,大量小对象的存在以及防止内存移动的需要是选择静态分配的原因。我对提到的原因没有清楚的了解。

虽然这里讲的是静态分配,但我从粗略的代码中看到的是,一块内存在应用程序启动时动态分配并保持事件状态直到应用程序结束,大致模拟了静态分配。

您能否解释一下在哪些情况下静态分配比按需动态分配更好,以便将其视为严重应用程序中的主要分配模式?

最佳答案

它更快,因为您避免了调用系统例程来管理存储的开销。 malloc()维护一个堆,所以每个请求都需要扫描一个适当大小的块,可能会调整块大小,更新块列表以将此块标记为已使用等。如果您要分配很多小对象,则此开销可能是过多的。使用静态分配,您可以创建一个分配池并只维护一个简单的位图来显示哪些区域正在使用中。这假设每个对象的大小相同,因此您通常为每个对象类型创建一个池。

关于memory - 在什么情况下静态分配比动态分配好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3214511/

相关文章:

java - 向 Java 类添加方法是否会增加其实例的内存使用量?

arrays - 为什么我不能将新分配的字节数组分配给类型为 []byte 的变量?

java - 根据 JVM 的内存粒度确定数组的最佳大小

c - 为 char 数组分配大小时出现段错误

c - 释放问题 ("realloc: invalid next size"后重新分配)

java - JMeter:64 位 Windows 操作系统可以增加多少 Java 堆大小

c++ - 将整型数组作为另一个不相关整型类型的数组进行访问的安全且符合标准的方法?

c++ - 在 C++ 中使用 std::unique_ptr 管理原始内存

python - panda3d 内存不足

java - hadoop的mapreduce中的详细数据流?