Question

Knowing that the class CCPoint has only two float member variables, is there any performance benefit to use the first example over the second one?

std::vector<p2t::Point*> polyline;
for (int i = 0; i < points.size(); ++i) {
    CCPoint p = points.at(i);
    polyline.push_back(new p2t::Point(p.x, p.y));
}

Put in other words, in this case, is this a good practice to use a local instance?

std::vector<p2t::Point*> polyline;
for (int i = 0; i < points.size(); ++i)
    polyline.push_back(new p2t::Point(points.at(i).x, points.at(i).y));

Thanks!

Was it helpful?

Solution 2

Here's how I would write that:

std::vector<std::unique_ptr<p2t::Point>> polyline;
for (const CCPoint& p : points)
    polyline.push_back(std::unique_ptr<p2t::Point>(new p2t::Point(p.x, p.y)));

Note use of a reference saves doing the lookup twice, but without copying the point. unique_ptr ensures the memory is later freed correctly with delete, you no longer need to do that yourself. And the range-based for creates shorter more readable code, and also avoids the redundant range-checking inside at().

In C++14 it gets even more efficient:

std::vector<std::unique_ptr<p2t::Point>> polyline;
for (const CCPoint& p : points)
    polyline.emplace_back(std::make_unique<p2t::Point>(p.x, p.y));

Note that storing points by pointer is not ideal from a performance perspective. That's something you usually do when you want a polymorphic collection. Does p2t::Point have virtual member functions?

OTHER TIPS

Never do optimizations before you've determined that this part of your code is really slowing down your application. The example with a local variable is better for understanding, so always use it in a first implementation. Anyway, compiler will probably generate the same code for the both in Release mode.

There is probably going to be a minor gain from not doing the lookup twice. Notice that you call at twice in the second example, but only once in the first.

With the modern compiler, it doesn't matter, it will generate the same code for both if optimization is on. To check that, you can turn on the compiler option /FA to generate the assembly code, if there're same, it means the compiler will take care of this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top