Quick Bench String Compares
Last updated on
I’ve done this before, had to compare strings, I was curious what a Quick Bench graph might give me.
Full Code
#include <string.h>
static void IntCmpBaseline(benchmark::State& state) {
uint32_t val1 = 123;
uint32_t val2 = 1234;
for (auto _ : state) {
bool eq = val1 == val2;
benchmark::DoNotOptimize(eq);
}
}
BENCHMARK(IntCmpBaseline);
static void StdStrCmp(benchmark::State& state) {
std::string str1("Some_quite_large_string1");
std::string str2("Fome_quite_large_string2");
for (auto _ : state) {
bool eq = str1 == str2;
benchmark::DoNotOptimize(eq);
}
}
BENCHMARK(StdStrCmp);
static void CStrStrcmp(benchmark::State& state) {
const char * str1 = "Some_quite_large_string1";
const char * str2 = "Fome_quite_large_string2";
for (auto _ : state) {
bool eq = !!(strcmp(str1,str2) == 0);
benchmark::DoNotOptimize(eq);
}
}
BENCHMARK(CStrStrcmp);
static void CStrFirstCharThenStrcmp(benchmark::State& state) {
const char * str1 = "Some_quite_large_string1";
const char * str2 = "Fome_quite_large_string2";
for (auto _ : state) {
bool eq = false;
uint32_t a = *(uint32_t*)str1;
uint32_t b = *(uint32_t*)str2;
if(a == b) {
eq = !!(strcmp(str1,str2) == 0);
}
benchmark::DoNotOptimize(eq);
}
}
BENCHMARK(CStrFirstCharThenStrcmp);
static void StdStrStrcmp(benchmark::State& state) {
std::string str1 = "Some_quite_large_string1";
std::string str2 = "Fome_quite_large_string2";
for (auto _ : state) {
bool eq = !!(strcmp(str1.c_str(),str2.c_str()) == 0);
benchmark::DoNotOptimize(eq);
}
}
BENCHMARK(StdStrStrcmp);
static void StdStrGetCStrEarlyStrcmp(benchmark::State& state) {
std::string str1 = "Some_quite_large_string1";
std::string str2 = "Fome_quite_large_string2";
const char *cstr1 = str1.c_str();
const char *cstr2 = str2.c_str();
for (auto _ : state) {
bool eq = !!(strcmp(cstr1, cstr2) == 0);
benchmark::DoNotOptimize(eq);
}
}
BENCHMARK(StdStrGetCStrEarlyStrcmp);
static void StdStrFirstCharThenStrcmp(benchmark::State& state) {
std::string str1 = "Some_quite_large_string1";
std::string str2 = "Fome_quite_large_string2";
for (auto _ : state) {
bool eq = false;
uint32_t a = *(uint32_t*)str1.c_str();
uint32_t b = *(uint32_t*)str2.c_str();
if(a == b) {
eq = !!(strcmp(str1.c_str(),str2.c_str()) == 0);
}
benchmark::DoNotOptimize(eq);
}
}
BENCHMARK(StdStrFirstCharThenStrcmp);