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.

And not only for string literals this is. Even better, for any kind of native array.

It might be called a “no brainer”. As soon as you figure it out, though.

And yes, we shall call it arrnlen and arrlen, too.

Much better vs ages-old  countof macro lying around.

Not very good, as noted numerous times:

    • Because macros carry no type, the implementation is not robust and bad usage won’t be detected at compilation time.
    • Macros can’t be overloaded which would be useful for containers.
    • Just like any macro, there are potential namespace collision issues.

So little C++ so much good!

The savings?

What are then the real-time savings of using this? Yes, it is quite hard to compute real-time savings.

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 native char arrays aka “string literals” your application processes.

The performance advantage vs. standard  char * based strlen and strnlen must be obvious, in some serious testing apps, someone has written to prove exactly “how much faster” is this.