Member-only story
The “Idiomatic” way of Testing for Empty Strings in Go- A Tempest in a Teapot?
During a recent Go code-review at my company I was advised to convert tests for empty strings from :
if len( mystring ) < 1 {}
which I was using, to:
if mystring == “” {}
A couple of decades of C++ experience taught me that, unless there’s some gnarly, instance specific compiler optimization being performed underneath the covers, in the latter comparison, a temporary object would have to be created in order to hold the empty string before the comparison could actually be done. After the temporary was created, then the code on the string object would be called to compare the two. So if you’re keeping track, that is:
- Construct an empty object on the stack, which means a̵l̵l̵o̵c̵a̵t̵i̵n̵g̵ borrowing memory and then executing the initialization code
- Compare your actual string to the empty object, which we know has a length of zero. Note that the comparison will (likely) involve another function call (complete with call stack and teardown)
This is madness, and is precisely why the std::string class in the Standard C++ Library has an empty() method to, you know, determine if a string is actually empty or not. This…