0

I have been working on some legacy C++ code and my objective is to optimize the code as much as possible. I was reading somewhere and found this code

// Bad Idea
class MyClass
{
public:
  void do_something(int i);
  void do_something(std::string str);
};


// Good Idea
class MyClass
{
public:
  void do_something(const int i);
  void do_something(const std::string &str);
};

This code says that use const as much as possible. Could someone explain if this has a significant performance improvement or if it is related to something else?

Impurity
  • 1,037
  • 2
  • 16
  • 31
Adithya
  • 241
  • 3
  • 16
  • 4
    ***if this has a significant performance improvement?*** That will depend on the code. – drescherjm Aug 21 '18 at 18:01
  • Step 1: Check the assembly. Step 2: Measure it. – tkausl Aug 21 '18 at 18:01
  • Code for correctness first. Are you going to modify `i` or `str`? If so making them const is not what you want to do. – NathanOliver Aug 21 '18 at 18:01
  • Microoptimizations are evil. – Evg Aug 21 '18 at 18:02
  • 1
    `const` generally does not affect performance. – Petr Skocik Aug 21 '18 at 18:02
  • @Evgeny It's that kinda thinking that leads to word programs with 5-minute boot times. – George Aug 21 '18 at 18:04
  • 3
    Using a `const std::string &` instead of `std::string` may save a copy, though if `do_something` is a sink you may instead disable a move and force a copy later on. – François Andrieux Aug 21 '18 at 18:05
  • @George, it better have 5-minute boot time than 5-minute crash time. – Evg Aug 21 '18 at 18:08
  • @Evgeny Optimisations/Micro Optimisations very rarely lead to crashes. It usually only happens when the code is already awful, or attempting to optimise out smart pointers from code that heavily relies on them (arguably code like that could fall under the "awful" category). – George Aug 21 '18 at 18:14
  • This question has been asked before. https://stackoverflow.com/questions/3435026/can-const-correctness-improve-performance The top post goes into fairly good detail about why constness doesn't improve performance but is still a good idea. – Thomas Kolarik Aug 21 '18 at 18:03

0 Answers0