Well, obviously you should get rid of all that stringstream stuff in favor of the straightforward
char buffer[100];
sprintf(buffer, "%016x", a ^ b);
return buffer;
That'll cut out all those virtual function calls and stateful stream operations in favor of just doing what you want: print a single integer in hex.
Also, you may not have noticed, but you're taking the parameters astr
and bstr
by value instead of by const reference, so depending on how you're calling this function, you might be spending most of your time making copies of std::string
objects, not hexifying them per se. My guess is that this is actually a bigger time sink than the stringstream stuff, even though that's what caught my eye first.
Therefore I'd try benchmarking
std::string xor_str(const std::string& astr, const std::string& bstr)
{
unsigned long a = strtoul(astr.c_str(), NULL, 16);
unsigned long b = strtoul(bstr.c_str(), NULL, 16);
char buffer[100]; // "big enough"
snprintf(buffer, sizeof buffer, "%016lx", a ^ b);
return buffer;
}
(Notice that you could use sprintf
instead, since in this particular case you know there can't be any overflow — and you are concerned about raw speed. But my assumption is that you aren't very good at profiling to find hotspots, and are looking for style tips in general, so the general advice "Always use snprintf
over sprintf
" wins out over the very case-specific and chainsawish "Omit bounds checks when you're sure they're unnecessary.")