inline bool f1ni(int i) { return i % 2 == 0; } TEST(OptionalTest, TestOptionalPerf) { auto f2 = [](int i) -> std::optional { if (i % 2 == 0) { return {}; } return i + 1; }; // run 1M cycles constexpr auto cycles = 100000000; nebula::common::Evidence::Duration duration; long sum2 = 0; for (int i = 0; i < cycles; ++i) { auto x = f2(i); if (x) { sum2 += x.value(); } } LOG(INFO) << fmt::format("optional approach: sum={0}, time={1}", sum2, duration.elapsedMs()); duration.reset(); long sum1 = 0; for (int i = 0; i < cycles; ++i) { if (i % 2 != 0) { sum1 += f1(i); } } LOG(INFO) << fmt::format("special value approach: sum={0}, time={1}", sum1, duration.elapsedMs()); EXPECT_EQ(sum1, sum2); -------------------------- Laptop Mac MacOs Mojave Processor 2.6 GHz Intel Core i7 /usr/bin/g++ --version > Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1 > Apple LLVM version 10.0.1 (clang-1001.0.46.4) > Target: x86_64-apple-darwin18.7.0 > Thread model: posix > InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin [Test Output] I0812 09:36:20.678683 348009920 TestCommon.cpp:354] optional approach: sum=2500000050000000, time=13 I0812 09:36:20.692001 348009920 TestCommon.cpp:363] special value approach: sum=2500000050000000, time=12 Linux Ubuntu 18.04 LTS 36 cores - one of them processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 85 model name : Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz stepping : 4 microcode : 0x100014a cpu MHz : 1685.329 cache size : 25344 KB physical id : 0 siblings : 36 core id : 0 cpu cores : 18 apicid : 0 initial apicid : 0 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves ida arat pku ospke /usr/bin/g++ --version > g++ (Ubuntu 9.1.0-2ubuntu2~18.04) 9.1.0 > Copyright (C) 2019 Free Software Foundation, Inc. [Test Output] I0812 16:42:07.391607 15080 TestCommon.cpp:354] optional approach: sum=2500000050000000, time=59 I0812 16:42:07.473335 15080 TestCommon.cpp:363] special value approach: sum=2500000050000000, time=81