From 8832700e25f2ed6507454e22d8f61fd027c8a59a Mon Sep 17 00:00:00 2001 From: lisyarus Date: Thu, 4 Dec 2025 18:11:11 +0300 Subject: [PATCH] Optimize math::length(vector) to prevent allocations for runtime-sized vectors --- libs/math/include/psemek/math/vector.hpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/libs/math/include/psemek/math/vector.hpp b/libs/math/include/psemek/math/vector.hpp index dc067e0f..fa017bb8 100644 --- a/libs/math/include/psemek/math/vector.hpp +++ b/libs/math/include/psemek/math/vector.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -286,17 +287,22 @@ namespace psemek::math using std::max; T r = abs(v[0]); for (std::size_t i = 1; i < v.dimension(); ++i) - r = max(r, abs(v[i])); + make_max(r, abs(v[i])); return r; } template T length(vector const & v) { - T const m = linf_norm(v); - if (m == T(0)) return m; + T const max = linf_norm(v); + if (max == T(0)) return max; + + T sum{}; + for (auto const & value : v.values()) + sum += sqr(value / max); + using std::sqrt; - return m * sqrt(length_sqr(v / m)); + return max * sqrt(sum); } template