Home > C++ > The Assumption Was Wrong

The Assumption Was Wrong

While performing maintenance on some legacy C++ code, a colleague came across a code fragment that performs a large, buffer-to-buffer byte copy. Instead of using the std::memcpy function to implement the copy, it was written the homegrown way – using a loop over the number of bytes to copy. The reason given for the choice was to “avoid the overhead of a function call“.

As the test code and results below show, the performance of std::memcpy blew away the loop-dee-loop strategy by a factor of 40X. The untested assumption behind the decision to write the loop was that std::memcpy was implemented under the covers as a loop by the compiler writers. An alternative assumption, that the compiler replaces std::memcpy with highly efficient, CPU-architecture-specific, inline code, either wasn’t known or it didn’t come to mind.

It took me about twenty minutes to prove, with objective data, that “the assumption was wrong“.

So, what’s the lesson here? There is none. It’s impractical to challenge and test every single assumption we make as programmers – and as people, no? Perhaps the original programmer was a newbie who hadn’t yet learned the rule of thumb that it’s almost always better to use compiler-supplied library functions and classes over equivalent homegrown code. Perhaps the assumption was so ingrained (like the theory X assumption that “anointed” superiors are smarter, more trustworthy, and more responsible than subordinates) it didn’t occur to the programmer to test it out. Perhaps it did occur to the programmer that he/she should test the assumption but he/she felt immense schedule pressure to plow ahead with blinders on.

Categories: C++ Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: