Home > Mobile >  Writing single-char vs. char const* to buffer
Writing single-char vs. char const* to buffer

Time:07-27

When writing single characters to an output stream, the purist in me wants to use single quotes (e.g.):

unsigned int age{40};
std::ostringstream oss;
oss << "In 2022, I am "      << age      << '\n';  // 1. Single quotes around \n
oss << "In 2023, I will be " << age   1u << "\n";  // 2. Minor ick--double quotes around \n

Because I'm writing a single character and not an arbitrary-length message, it doesn't seem necessary to have to provide a null-terminated string literal.

So I decided to measure the difference in speed. Naively, I'd expect option 1, the single-character version, to be faster (only one char, no need to handle \0). However, my test with Clang 13 on quick-bench indicates that option 2 is a hair faster. Is there an obvious reason for this?

https://quick-bench.com/q/3Zcp62Yfw_LMbh608cwHeCc0Nd4

Of course, if the program is spending a lot of time writing data to a stream anyway, chances are the program needs to be rethought. But I'd like to have a reasonably correct mental model, and because the opposite happened wrt what I expected, my model needs to be revised.

CodePudding user response:

As you can see in the assembly and in the libc source here, both << operations in the end call the same function __put_character_sequence which the compiler decided to not inline in either case.

So, in the end you are passing a pointer to the single char object anyway and if there is a pointer indirection overhead it applies equally to both cases.

__put_character_sequence also takes the length of the string as argument, which the compiler can easily evaluate at compile-time for "\n" as well. So there is no benefit there any way either.

In the end it probably comes down to the compiler having to store the single character on the stack since without inlining it can't tell whether __put_character_sequence will modify it. (The string literal cannot be modified by the function and also would have the same identity between iterations of the loop.)

If the standard library used a different approach or the compiler did inline slightly differently, the result could easily be the other way around.

  •  Tags:  
  • c
  • Related