Why is this so much slower in C++?

后端 未结 9 2010
盖世英雄少女心
盖世英雄少女心 2020-12-31 11:49

I have converted this simple method from C# to C++. It reads a path table and populates a list of lists of ints (or a vector of vectors of ints).

A sample line from

9条回答
  •  别那么骄傲
    2020-12-31 12:29

    Both List.Add and vector::push_back reallocate memory from time to time as the container grows. C++ vector stores subvectors by value, so all their data (which seem to be huge in your case) is copied again and again. In contrast, C# list stores sublists by reference, so sublists' data is not copied during reallocation.

    Typical vector implementation doubles its capacity during reallocation. So if you have 1 million of lines, subvectors will be copied log(2,1000000) ≈ 10 times.

    Move semantics introduced in C++11 is supposed to eliminate this effect. Until that, try vector< shared_ptr< vector > >, list< vector >, or, if you know future size in advance, use vector::reserve() to avoid reallocations.

提交回复
热议问题