为什么递归内存释放这么慢?

时间:2013-08-01 20:02:45

标签: c++ performance memory-management heap-memory

我做了一个八叉树快速匹配三维点。它很快!但是,删除八叉树比构建它需要多100倍的时间。我不明白为什么会这样。这是我的班级:

#pragma once
#include "LeakCheck.h"
#include "vec3.h"

namespace Geometry 
{

static const float tolerance = 1.0e-30f;

class VertexOctree
{
private:
    float halfSize;
    vec3 center;
    VertexOctree *subTrees;
    int vertexIndex;
    void CreateSubTree()
    {
        subTrees = news VertexOctree[8];
        subTrees[0] = VertexOctree(center+(vec3(-1.0f,-1.0f,-1.0f)*halfSize),halfSize*0.5f);
        subTrees[1] = VertexOctree(center+(vec3(+1.0f,-1.0f,-1.0f)*halfSize),halfSize*0.5f);
        subTrees[2] = VertexOctree(center+(vec3(-1.0f,+1.0f,-1.0f)*halfSize),halfSize*0.5f);
        subTrees[3] = VertexOctree(center+(vec3(+1.0f,+1.0f,-1.0f)*halfSize),halfSize*0.5f);
        subTrees[4] = VertexOctree(center+(vec3(-1.0f,-1.0f,+1.0f)*halfSize),halfSize*0.5f);
        subTrees[5] = VertexOctree(center+(vec3(+1.0f,-1.0f,+1.0f)*halfSize),halfSize*0.5f);
        subTrees[6] = VertexOctree(center+(vec3(-1.0f,+1.0f,+1.0f)*halfSize),halfSize*0.5f);
        subTrees[7] = VertexOctree(center+(vec3(+1.0f,+1.0f,+1.0f)*halfSize),halfSize*0.5f);
    }
public:
    int AddVertex(std::vector<vec3> &VertexList, const vec3& Point)
    {
        if (vertexIndex == -1) {
            vertexIndex = VertexList.size();
            VertexList.push_back(Point);
            return vertexIndex;
        }
        if ((VertexList[vertexIndex]-Point).lengthSq() < tolerance) {
            return vertexIndex;
        }
        if (subTrees == NULL)
            CreateSubTree();

        return subTrees[(Point.x>center.x)+(2*(Point.y>center.y))+(4*(Point.z>center.z))].AddVertex(VertexList, Point);
    }
    VertexOctree()
    {
        subTrees = NULL;
        vertexIndex = -1;
    }
    VertexOctree(vec3 Center, float HalfSize)
    {
        subTrees = NULL;
        center = Center;
        halfSize = HalfSize;
        vertexIndex = -1;
    }
    ~VertexOctree()
    {
        if (subTrees)
            delete[] subTrees;
    }
};

};

删除VertexOctree时需要很长时间。比创建树还要长得多,这些树也必须进行浮点运算来比较点并分配内存。为什么删除它这么慢?我使用Visual Studio 2012并在发布模式下编译。

1 个答案:

答案 0 :(得分:4)

按F5运行程序时,即使在发布模式下,它也会使用一个特殊的,较慢的调试堆。如果按ctrl + F5,即使在调试模式下,它也会使用常规堆。尝试一下,如果它加快了速度,那么在项目的调试属性中,在环境框中输入_NO_DEBUG_HEAP = 1来始终使用快速堆。