Assigning an array of std :: vector slows down the subsequent calculation

I was optimizing an algorithm. I ran into a strange oddity.

The following:

//The following is completely unused
vector<int>** rotated_squares;
rotated_squares = new vector<int>*[31];
for (int i=0;i<31;++i) {
    rotated_squares[i] = new vector<int>[31];

    //Lots of computation, using other vectors, but not rotated_squares

. . . is at least ten times slower than:

    //The exact same computation as above.

I have no idea what could be causing this. The only thing I can think of is that it is an artifact of the underlying implementation somehow. To that end, using Visual Studio 2010 for C++ compiler.

EDIT: Clarification, the computation below is the part that becomes slower. The memory allocations at the top are almost negligible when profiling.

So the issue is that I add the lines at the top, and the code runs about ten times slower. By debugging, the extra memory allocation takes a fraction of a second, but the computation code, which normally takes about eight seconds, starts to take several minutes.

EDIT: By popular demand, the source of the algorithm can be found here: The point is that the #if 1 can be set or unset and the code compiles fine--but with it, it runs much slower in the computation section.

EDIT: I have reduced the code to the following: In my code, this causes the problem. However, making a simple test case (i.e. a main function with just this code) does not show the problem.

With C+++03 and a std::vector< T const > you've passed into Undefined Behavior land. I am not sure of the situation with C++11, even after using like 10 minutes trawling the standard. But possibly the same, and in that case no special explanation is needed.

However, it might be that the code that you haven't shown, and that's allegedly slowing down, is referencing rotated_squares.

It might also be that the added code causes a cache miss.

It's rather difficult to reproduce without the code, but it just might help to put the slowed-down code in its own function.

Engaging ESP circuit overdrive… Concentrating… Nope, that didn't work either.