1

Sorry if this really doesn't make sense, but I'm curious if it matters. Which is faster:

std::cout << String1 << String2;

Or:

string String2 = "Some Text" + String1;
std::cout << String2;
xskxzr
  • 12,442
  • 12
  • 37
  • 77
  • 8
    What's preventing you from benchmarking it? – UnholySheep Aug 10 '21 at 17:57
  • How would I be able to achive that? – The Doge Master Aug 10 '21 at 17:58
  • 2
    Read e.g.: https://stackoverflow.com/questions/49044422/how-can-i-benchmark-the-performance-of-c-code – UnholySheep Aug 10 '21 at 18:00
  • I guess writing to stream would be faster. – macroland Aug 10 '21 at 18:00
  • sorry for wasting time.? Although idk how i'd implement that – The Doge Master Aug 10 '21 at 18:00
  • Write a program (or function) using the first method. Write another program (or a different function in the same program) using the second method. Run them both and see which is quicker. You'll probably need to run them both lots of times to get useful, stable measurements, but the linked question goes into all that. – Useless Aug 10 '21 at 18:03
  • If you want to know which is faster, use a benchmark tool like this one: https://quick-bench.com/ – NathanOliver Aug 10 '21 at 18:06
  • This might depend on a lot of variables. Maybe it depends on the length of the strings, on how the stream is implemented in the standard library you are using, maybe even on what the stream pipes to. It's possible that one of these approaches it always better than the other, but more likely than not there exists circumstances where one is better, and other circumstances where the other is better. – François Andrieux Aug 10 '21 at 18:07
  • 1
    IMHO, printing the strings is faster. When concatenating strings, the end of the string has to be located, then the second string is appended. The string may have to perform memory reallocation. Printing a string is a one pass endeavor without any memory allocations. – Thomas Matthews Aug 10 '21 at 18:21
  • 1
    Almost same: https://quick-bench.com/q/FVVX0Uns5Lf8GNYM0SRjxyiiIgs Summing strings minimally better. – Robert Andrzejuk Aug 10 '21 at 18:49
  • 2
    Did you mean the first case to be `std::cout << "Some Text" << String1;` by chance? It doesn't look like we're comparing apples to apples. – Tim Randall Aug 10 '21 at 18:49
  • Wanted to minimize the amount of time writting. – The Doge Master Aug 17 '21 at 22:49
  • Just actually realized i think that was intentional, although i don't know why. – The Doge Master Aug 17 '21 at 22:52
  • This question still is left unanswered stackoverflow wise – The Doge Master Aug 23 '21 at 16:28

0 Answers0