gpt4 book ai didi

c++ - 编译器内存优化 - 重用现有 block

转载 作者:太空狗 更新时间:2023-10-29 20:21:42 24 4
gpt4 key购买 nike

假设我要分配 2 个内存块。我使用第一个内存块来存储一些东西并使用这个存储的数据。然后我使用第二个内存块做类似的事情。

{
int a[10];
int b[10];

setup_0(a);
use_0(a);

setup_1(b);
use_1(b);
}

|| compiler optimizes this to this?
\/

{
int a[10];

setup_0(a);
use_0(a);

setup_1(a);
use_1(a);
}

// the setup functions overwrites all 10 words

现在的问题是:如果编译器知道第一个 block 不会被再次引用,编译器是否优化它,以便它们重用现有的内存块,而不是分配第二个内存块?

如果这是真的:这也适用于动态内存分配吗?如果内存持续存在于范围之外,但以与示例中给出的方式相同的方式使用,这是否也可能?我假设这仅在 setup 和 foo 在同一个 c 文件中实现(与调用代码存在于同一个对象中)时才有效?

最佳答案

Do compiler optimize this

这个问题只有在你询问特定的编译器时才能得到回答。通过检查生成的代码可以找到答案。

so that they reuse the existing memory blocks, instead of allocating a second one, if the compiler knows that the first block will not be referenced again?

这样的优化不会改变程序的行为,所以它是被允许的。另一个问题是:是否可能证明内存不会被引用?如果可能,那么在合理的时间内证明是否足够容易?我可以很安全地说,一般情况下无法证明,但在某些情况下是可以证明的。

I assume this only works if setup and foo are implemented in the same c file (exist in the same object as the calling code)?

这通常需要证明内存的不可触及性。理论上,链接时间优化可能会提升这一要求。

Does this also work with dynamic memory allocation?

理论上,因为它不会改变程序的行为。但是,动态内存分配通常由库执行,因此编译器可能无法证明没有副作用,因此无法证明删除分配不会改变行为。

Is this also possible if the memory persists outside the scope, but is used in the same way as given in the example?

如果编译器能够证明内存泄漏,那么也许。


即使可能进行优化,也不是很重要。节省一点堆栈空间可能对运行时间影响很小。如果数组很大,它可能有助于防止堆栈溢出。

关于c++ - 编译器内存优化 - 重用现有 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41897268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com