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.
// g++ prog.cc -Wall -Wextra -std=c++14 #include <cstdlib> #include <cassert> namespace dbj { template<typename T, size_t N> inline constexpr size_t arrnlen(const T(&)[N], const size_t & maxlen) { return std::min(N, maxlen) - 1; } template<typename T, size_t N> inline constexpr size_t arrlen(const T(&)[N]) { return N - 1; } } int main() { /* declaration of string literals made up of four main char types */ char promptA[] = "0123456789"; wchar_t promptW[] = L"0123456789"; char16_t prompt16[] = u"0123456789"; char32_t prompt32[] = U"0123456789"; static_assert( dbj::arrnlen(promptA, BUFSIZ) == 10 ); static_assert( dbj::arrnlen(promptW, BUFSIZ) == 10 ); static_assert( dbj::arrnlen(prompt16, BUFSIZ) == 10 ); static_assert( dbj::arrnlen(prompt32, BUFSIZ) == 10 ); }
And yes, we shall call it arrnlen
and arrlen
, too.
Much better vs ages-old countof
macro lying around.
#define countof(arr) sizeof(arr) / sizeof(arr[0])
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.
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.