Optimizing by executing less code
suggest changeThe most straightforward approach to optimizing is by executing less code. This approach usually gives a fixed speed-up without changing the time complexity of the code.
Even though this approach gives you a clear speedup, this will only give noticeable improvements when the code is called a lot.
Removing useless code
void func(const A *a); // Some random function
// heap allocation and matching deallocation
auto a1 = std::make_unique<A>();
func(a1.get());
// the object lives in automatic storage
auto a2 = A{};
func(&a2);
Since C++14, a compiler may omit a call to a replaceable global allocation function and its matching deallocation, even when the allocated object is used. That does not remove the constructor or the call to func.
Doing code only once
std::map<std::string, std::unique_ptr<A>> lookup;
// Slow insertion/lookup.
// find and operator[] each search the map. emplace searches again when the key is absent.
const A *lazyLookupSlow(const std::string &key) {
if (lookup.find(key) == lookup.end())
lookup.emplace(key, std::make_unique<A>());
return lookup[key].get();
}
// operator[] searches once and value-initializes a null unique_ptr when the key is absent.
const A *lazyLookupFast(const std::string &key) {
auto &value = lookup[key];
if (!value)
value = std::make_unique<A>();
return value.get();
}
A similar approach to this optimization can be used to implement a stable version of unique
std::vector<std::string> stableUnique(const std::vector<std::string> &v) {
std::vector<std::string> result;
std::set<std::string> checkUnique;
for (const auto &s : v) {
// insert reports whether the string was new, so a separate search is unnecessary
if (checkUnique.insert(s).second)
result.push_back(s);
}
return result;
}
Preventing useless reallocating and copying/moving
The previous example still searches the std::set inside insert. The std::vector may also reallocate as it grows. Reserving the maximum size prevents those reallocations. push_back still copies each new string into the vector.
std::vector<std::string> stableUnique(const std::vector<std::string> &v) {
std::vector<std::string> result;
// reserve avoids later reallocations. Duplicate strings make this larger than the final size.
result.reserve(v.size());
std::set<std::string> checkUnique;
for (const auto &s : v) {
// See example above
if (checkUnique.insert(s).second)
result.push_back(s);
}
return result;
}