Thursday, April 24, 2008

STL strings

So, while reviewing someone's code, I ran into a place where it was possible to eliminate an unnecessary string assignment. Which got me thinking - is mentioning this even worth it? How expensive is a string assignment, anyway?

So I wrote this simple program:

#define _SECURE_SCL 0

#include <string>

using namespace std;

void f(string a, string *b) {
*b = a;
}

int main(int argc, char **argv) {
string y = argv[0];
string x;
f(y, &x);
return 0;
}

and stepped through it in the disassembler. The function f itself was inlined, so I only counted... prepare... the instructions in this call:

call dword ptr [__imp_std::basic_string<char,std::char_traits<char>,std::allocator<char> >::operator= (402048h)]

I skipped the call to new (argv[0] turns out to be 69 bytes, just above the default string buffer, so it does allocate), and memcpy itself (memcpy_s to be exact). The net result was - 270+ instructions. If there is no allocation, it is ~150!

This is correct - anywhere between 150 and 270 instructions of STL goo per string assignment IN ADDITION TO ACTUALLY DOING THE WORK!

I tried to do the same on Linux, and after 70-something ddd hung disassembling one of the functions...

3 comments:

Илья Казначеев said...

You should not use C++ in 2008.

Except if you're doing GUI.

But if you're doing GUI you shouldn't care about 100 instructions here, 100 instructions there: User isn't going to react faster than your code accepts his reactions, or you're doing something of the other kind of wrong.

Sergey Solyanik said...

I don't think Linux was all that much different. I went through 70 instructions before the debugger hung, and I don't think it was even half-way there :-)...

Eldar said...

Actually, there is a lot of cases when you use C++ in 2008. There is also a lot of cases, when you use C in 2008. I am not sure what Serge is using it for at Google, but at Microsoft it's a very common case. I just went off using C# for 3 months in a row, and have to get back to C++ because the platform does not have anything more decent. It's just life.