02 June 2023

C++ 核心指南目录

“Don’t assume that complicated code is necessarily faster than simple code”

理由

简单代码也能很快。优化器有时能优化简单代码,且极其显著。

好例子

// clear expression of intent, fast execution
vector<uint8_t> v(100000);

for (auto& c : v)
    c = ~c;

目的明确,速度极快。

坏例子

// intended to be faster, but is often slower
vector<uint8_t> v(100000);

for (size_t i = 0; i < v.size(); i += sizeof(uint64_t)) {
    uint64_t& quad_word = *reinterpret_cast<uint64_t*>(&v[i]);
    quad_word = ~quad_word;
}

想要更快,经常很慢。