C++ Zero time strlen and strnlen.

Zero time strlen and strnlen? I am reasonably sure it is not me who first thought of this, but today, I figured writing a “zero time” strlen() and strnlen() in modern C++ is actually possible and obvious. Not for pointers though. For arrays of characters that is.

Update 2017-10-19

A “proper” and tested  modern C++ code is to be found HERE as the part of dbj++, on GitHub.  dbj::strlen() and dbj::strnlen() to take proper care of char, wchar_t, char16_t and char32_t.

Usage? If you need strlen() or strnlen() just use dbj::strlen() or dbj::strnlen(). In case you are passing arrays of characters the execution time is “zero”.

For example:

All  of the dbj::strnlen() calls above will take “zero” time to execute. And whatever is the (legal) size of the arrays used the execution time will be still “zero”.

So little C++ so much good!

Zero time strlen and strnlen. The initial idea

What are then the real-time savings of using this? Yes, it is quite hard to compute., them real time savings, if your app uses the code below.
It may be hard but it is obvious there must be a time-saving. It depends on the compiler on the OS and on the number of char arrays your application processes.

wchar_t version is trivial so it is a proverbial “exercise for the reader”.

Copy/paste and try. It should work “out of the box”.  Coliru version is here.

This little “nugget” shows, perhaps dramatically, the advantages of using modern C++ compilers.

For more modern C++ speculations and more copy paste opportunities, please click HERE .

Enjoy …? No, wait! There is more!

Obviously, the same concept can be (and already is) extended to an geenric array of T. Above will work for any T, for which the std:::min() will work.