c++ - Is boost regex slower than this combination of isupper and isdigit? -
i need check whether string consists of special set of characters (abcdefghijklmnopqrstuvwxyz0123456789<
).
i either use boost regex or combination of isupper
, isdigit
. 1 considered better choice when comes performance? string lenghts testing around 100 characters.
bool isvalid(string& rstring) { boost::regex regex("[0123456789abcdefghijklmnopqrstuvwxyz<]+"); boost::cmatch match; return boost::regex_match(rstring.c_str(), match, regex); } bool isvalid(string& rstring) { (string::size_type = 0; < rstring.size(); ++i) if (!isupper(rstring[i])) if (!isdigit(rstring[i])) if (rstring[i] != '<') return false; return true; }
is yyy slower yyy ?
answer: time it
in case (swapping boost::regex std::regex):
#include <vector> #include <iostream> #include <iomanip> #include <regex> bool isvalid1(std::string const& rstring) { static const std::regex regex("[0-9a-z<]+"); return std::regex_match(rstring, regex); } bool isvalid2(std::string const& rstring) { (std::string::size_type = 0; < rstring.size(); ++i) if (!std::isupper(rstring[i])) if (!std::isdigit(rstring[i])) if (rstring[i] != '<') return false; return true; } auto make_samples = []() { std::vector<std::string> result; result.reserve(100000); std::generate_n(std::back_inserter(result), 100000, [] { if (rand() < (rand_max / 2)) { return std::string("abcdef34<63dfgs"); } else { return std::string("abcdef34<63dfgs"); } }); return result; }; int main() { auto samples = make_samples(); auto time = [](const char* message, auto&& func) { clock_t tstart = clock(); auto result = func(); clock_t tend = clock(); std::cout << message << " yields " << result << " in " << std::fixed << std::setprecision(2) << (double(tend - tstart) / clocks_per_sec) << '\n'; }; time("regex method: ", [&]()->std::size_t { return std::count_if(samples.begin(), samples.end(), isvalid1); }); time("search method: ", [&]()->std::size_t { return std::count_if(samples.begin(), samples.end(), isvalid2); }); }
sample results:
regex method: yields 49816 in 1.29 search method: yields 49816 in 0.04
Comments
Post a Comment