C++ Array vs vector

前端 未结 8 993
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 06:06

when using C++ vector, time spent is 718 milliseconds, while when I use Array, time is almost 0 milliseconds.

Why so much performance difference?

int         


        
相关标签:
8条回答
  • 2021-01-03 06:50

    You are probably using VC++, in which case by default standard library components perform many checks at run-time (e.g whether index is in range). These checks can be turned off by defining some macros as 0 (I think _SECURE_SCL).

    Another thing is that I can't even run your code as is: the automatic array is way too large for the stack. When I make it global, then with MingW 3.5 the times I get are 627 ms for the vector and 26875 ms (!!) for the array, which indicates there are really big problems with an array of this size.

    As to this particular operation (filling with value 1), you could use the vector's constructor:

    std::vector<int> v(size * size, 1);
    

    and the fill algorithm for the array:

    std::fill(arr, arr + size * size, 1);
    
    0 讨论(0)
  • 2021-01-03 06:53

    When you declare the array, it lives in the stack (or in static memory zone), which it's very fast, but can't increase its size.

    When you declare the vector, it assign dynamic memory, which it's not so fast, but is more flexible in the memory allocation, so you can change the size and not dimension it to the maximum size.

    0 讨论(0)
提交回复
热议问题