这个程序在“返回”后需要很长时间才能关闭;在主()

Jos*_* D. 5 c++ performance destructor

这是我正在处理的代码:

#include <iostream>
#include <map>

using namespace std;

static unsigned long collatzLength(unsigned long n) {
    static std::map<unsigned long,int> collatzMap;
    int mapResult = collatzMap[n];
    if (mapResult != 0) return mapResult;

    if (n == 1) {
        return 1;
    } else { 
        collatzMap[n] = 1 + collatzLength(n%2==0?n/2:3*n+1);
        return collatzMap[n];
    }
}

int main() {
    int maxIndex = 1;
    unsigned int max = 1;
    for (int i=1; i<1000000; i++) {
        //cout<<i<<endl;
        unsigned long count = collatzLength(i);
        if (count > max) {
            maxIndex = i;
            max = count;
        }
    }
    cout<<maxIndex<<endl;
    getchar();
    cout<<"Returning..."<<endl;
    return maxIndex;
}
Run Code Online (Sandbox Code Playgroud)

当我编译并运行这个程序时(使用 Visual Studio 2012 和 Release 构建设置),在程序打印“Returning...”后需要 10 秒(在我的电脑上)关闭

这是为什么?

注意:我知道这个程序写得不好,我可能不应该在 collat​​zLength 上使用“静态”,也不应该为该函数使用缓存,但我对如何改进此代码不感兴趣,我只是有趣的是为什么关闭需要这么多时间。

Nei*_*irk 4

转到启动项目的项目设置“调试”部分。进入_NO_DEBUG_HEAP=1Environment部分。即使在发布模式下也需要执行此操作。