Why is this so much slower in C++?

后端 未结 9 2085
盖世英雄少女心
盖世英雄少女心 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:34

    I'm not exactly sure what is going on here, but I see a few ways in which you can optimize your code. If this doesn't get you there, then there might be something else going on.


    How big are your strings? As you are passing them in your C++ version, you are making copies because you are "passing by value". Try passing it by constant reference:

    void Level::PopulatePathVectors(const string &pathTable)
    

    This passes the object by reference, meaning it is not making a copy. Then, it is customary to make it const to ensure that it is not getting modified in your function.


    Use .append or += to extend tempString. I believe you are making a new string object, then replacing the old one with just +, while += and .append are going to modify the current one in place:

    tempString.append(line[count]);
    

    You can also tweak out a bit more performance by declaring your variables at the top and then reassigning into them. This will prevent them from getting recreated every time. For example, put string line; before your for-loop, because it's going to get overwritten anyways.

    There are a few places you can do this, such as with tempString.

提交回复
热议问题