In @src/routenodes.cpp , can we change some vector to array for better performance? ---…
- User
In @src/routenodes.cpp , can we change some
vectortoarrayfor better performance? --- Content from referenced files --- Content from @C:\routenodes\src\routenodes.cpp: // 计算所求路径的核心代码#include "routenodes.hpp"
#include #include #include #include
namespace routenodes {
// 拐点惩罚系数 const float BendPenalty = 100.0f; // 路径重叠惩罚系数 const float PathOverlapPenalty = 2.0f; // 路径居中奖励系数 const float PathMiddleReward = 0.9f;
// 生成已有路径周围扩大一圈余量的矩形 void initPathRects(const CompAndCanvasInfo& wsg, std::vector& pathRects) { // 预留的数组大小 size_t cap = 0; for (const auto& path : wsg.paths) { if (path.size() > 1) { cap += path.size() - 1; } }
codepathRects.reserve(cap); for (const auto& path : wsg.paths) { for (size_t i = 0; i < path.size() - 1; ++i) { const auto& point = path[i]; const auto& next = path[i + 1]; pathRects.push_back({ std::min(point.x, next.x) - DefaultPathMargin, std::max(point.x, next.x) + DefaultPathMargin, std::min(point.y, next.y) - DefaultPathMargin, std::max(point.y, next.y) + DefaultPathMargin, }); } }}
using MidLines = std::vector<std::pair<CustomPoint, CustomPoint>>;
void findMidLines(const CompAndCanvasInfo& wsg, MidLines& midLines) { // 求所有极大空矩形 std::vector inRects; inRects.reserve(wsg.compPartInfos.size()); for (const auto& comp : wsg.compPartInfos) { inRects.push_back(Rect(comp)); }
codeconst Rect canvas = {0.0f, wsg.graphicSceneWidth, 0.0f, wsg.graphicSceneHeight}; std::vector<Rect> maxEmptyRects; findMaxEmptyRects(inRects, canvas, maxEmptyRects); midLines.reserve(maxEmptyRects.size() * 2); for (const auto& rect : maxEmptyRects) { // 如果空矩形的左右不与画布边界重合,且左右距离大于两倍余量,则考虑竖直中线 if (!isClose(rect.left, canvas.left) && !isClose(rect.right, canvas.right) && rect.right - rect.left > 2.0f * DefaultMargin) { const float x = (rect.left + rect.right) / 2; midLines.push_back({{x, rect.top}, {x, rect.bottom}}); } // 同理考虑水平中线 if (!isClose(rect.top, canvas.top) && !isClose(rect.bottom, canvas.bottom) && rect.bottom - rect.top > 2.0f * DefaultMargin) { const float y = (rect.top + rect.bottom) / 2; midLines.push_back({{rect.left, y}, {rect.right, y}}); } } Assistant
Yes, I can do that. Using
std::arrayfor fixed-size inner containers within astd::vectorcan improve performance by reducing heap allocations and improving data locality.In
findShortestPath, thedistandparentvectors have inner vectors of a fixed size of 2 (for horizontal and vertical states). These are good candidates forstd::array.I will make the following changes:
- Add the
<array>header. - Change the types of
distandparentinfindShortestPathto usestd::array.
- Add the
Assistant
I have made the requested changes to
src/routenodes.cpp. Thedistandparentvectors infindShortestPathnow usestd::arrayfor their inner containers, which should provide a performance improvement.