diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp index e0562c8bd..4e80185a4 100644 --- a/include/nlohmann/detail/output/serializer.hpp +++ b/include/nlohmann/detail/output/serializer.hpp @@ -1510,7 +1510,19 @@ class serializer { flush(); } - std::memcpy(write_buffer.data() + write_buffer_pos, s, length); +#if defined(__GNUC__) && !defined(__clang__) + std::size_t copy_length = length; + // GCC knows from the test above that the length is below the size of + // the write buffer, and with that bound it may expand the memcpy into + // "rep movsq" (seen with -march=x86-64-v3 and -mtune=generic) instead + // of calling memcpy. For the short runs written here its start-up cost + // is far above that of the call (dump() with ensure_ascii 80 % slower + // on Sapphire Rapids), so hide the bound from the optimizer. + __asm__("" : "+r"(copy_length)); +#else + const std::size_t copy_length = length; +#endif + std::memcpy(write_buffer.data() + write_buffer_pos, s, copy_length); write_buffer_pos += length; } diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 44a5b6cd1..25e757934 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -39101,7 +39101,19 @@ class serializer { flush(); } - std::memcpy(write_buffer.data() + write_buffer_pos, s, length); +#if defined(__GNUC__) && !defined(__clang__) + std::size_t copy_length = length; + // GCC knows from the test above that the length is below the size of + // the write buffer, and with that bound it may expand the memcpy into + // "rep movsq" (seen with -march=x86-64-v3 and -mtune=generic) instead + // of calling memcpy. For the short runs written here its start-up cost + // is far above that of the call (dump() with ensure_ascii 80 % slower + // on Sapphire Rapids), so hide the bound from the optimizer. + __asm__("" : "+r"(copy_length)); +#else + const std::size_t copy_length = length; +#endif + std::memcpy(write_buffer.data() + write_buffer_pos, s, copy_length); write_buffer_pos += length; }