为什么删除后多维数组的性能提升如此之大?

问题描述 投票:0回答:0

我在用下面这段代码测试多维数组的性能时发现,如果在for循环后面加上

delete[] a[i]
,总的执行时间只有不加
delete[] a[i]
的情况的九分之一。使用 Visual Studio 2023 x86 发布和调试模式进行测试。为什么性能差异如此之大?

struct Rgb
{
    int r;
    int g;
    int b;
};

#define M 8000
#define N 5000

void draw()
{
    Timer timer; // For benchmark, calculate execution time
    Rgb** a = new Rgb * [M];
    for (int i = 0; i < M; i++)
    {
        a[i] = new Rgb[N];
        for (int j = 0; j < N; j++)
        {
            a[i][j] = { 1,2,3 };
        }
        //delete[] a[i]; //With this sentance, in release mode ,draw() execution takes only 17ms, otherwise takes 152ms. In debug mode, draw() execution takes only 73ms, otherwise takes 238ms
    }
    //delete[] a;
}

int main()
{
    draw();
}

经benchmark测试,在release模式下,

draw()
执行仅需17ms,否则需152ms。在调试模式下,
draw()
执行只需要 73ms,否则需要 238ms

c++ multidimensional-array visual-c++ c++17
© www.soinside.com 2019 - 2024. All rights reserved.