cppfront icon indicating copy to clipboard operation
cppfront copied to clipboard

Avoid string allocation/free traffic in assert_in_bounds()

Open ishani opened this issue 2 months ago • 1 comments

Move the construction of the OOB violation string to after the OOB check fails so that the code is not allocating, concatenating and freeing strings that are never used in regular operation. The change simply shunts the construction of the msg string inside the bounds check, given that the msg result is only ever used when the condition fails.

Discovered this by accident when an RNG class I had ported to cpp2 was reading and writing to a small fixed-size array and the RNG was used very frequently in an inner loop.

Profiling the app (-O3 build, clang 19) showed considerable work being done building and discarding strings for every access of the std::array member. Although that could be mitigated by switching to unchecked_subscript, avoiding this string build does not change the operation of the check but does remove the penalty.

ishani avatar Oct 22 '25 19:10 ishani

I recommend viewing this with whitespace ignored, as it is then a single line move instead of multiple lines moved.

gregmarr avatar Oct 23 '25 01:10 gregmarr