只是想知道是否建议使用这种代码来提高性能?
void functionCalledLotsofTimes() {
static int *localarray = NULL;
//size is a large constant > 10 000
if (localarray == NULL) localarray = new int[size];
//Algorithm goes here
}
我也很好奇像 g++ 这样的现代 c++ 编译器是如何实现静态变量的。它们是否像全局变量一样处理?
最佳答案
不推荐,因为你是在给一个函数引入全局状态。当函数中有全局状态时,就会产生副作用。副作用会导致问题,尤其是在多线程程序中。
参见 Referential Transparency想要查询更多的信息。对于相同的输入,您总是希望有相同的输出,无论您使用多少线程。
如果要提高效率,允许用户自己指定缓冲区作为参数之一。
查看 global and static variables here 之间的区别.
关于c++ - 在 C++ 中重用内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2331306/