c++ - Is there a C++11 strncmp alternative that performs as well? -
i want prefix in string. have been using this:
if (s.substr (0, 7) == "prefix_") ...
while works, relatively slower strncmp
, shown test:
#include <iostream> #include <chrono> #include <string> #include <string.h> int main () { std::string s = "prefix_this passing test match"; auto t0 = std::chrono::high_resolution_clock::now (); (int = 0; < 1000000; i++) if (s.substr (0, 7) == "prefix_") ; auto t1 = std::chrono::high_resolution_clock::now (); (int = 0; < 1000000; i++) if (! s.compare (0, 7, "prefix_", 0, 7)) ; auto t2 = std::chrono::high_resolution_clock::now (); (int = 0; < 1000000; i++) if (! strncmp (s.c_str (), "prefix_", 7)) ; auto t3 = std::chrono::high_resolution_clock::now (); std::cout << "[1] s.substr (0, 7) == \"prefix_\" " << std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count() << " μs\n" << "[2] ! strncmp (s.c_str (), \"prefix_\", 7) " << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() << " μs\n" << "[3] ! s.compare (0, 7, \"prefix_\", 0, 7) " << std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count() << " μs\n"; return 0; }
i seeing performance, surprised me:
[1] s.substr (0, 7) == "prefix_" 33022 μs [2] ! strncmp (s.c_str (), "prefix_", 7) 32547 μs [3] ! s.compare (0, 7, "prefix_", 0, 7) 12953 μs
i prefer use c++11, without dropping libc, results not good.
yes.
you may avoid string construction following, actual analogue strncmp
:
if (s.compare(0, 7, "prefix_") == 0) {}
in reality, of course, i'd recommend not hardcoding n value.
as always, spending 5 minutes perusing standard library reference goes long way…
Comments
Post a Comment