On your question, it seems that you already know about the philosophy of “premature optimization of evil,” so I will not preach about it. :)
Modern compilers are already pretty smart at micro optimization for you. If you try too hard, you can often do something slower than the original straightforward code.
For small "optimizations" you can safely and without hesitation, and this does not affect the readability / portability of the code, check the section "Premature pessimization" in the book "C ++ Coding Standards" by Sutter and Alexandrescu.
For more optimization methods, check out Efficient C ++ from Bulka and Mayhew. Use only if warranted by profiling!
For good general C ++ programming rules, check:
- C ++ coding standards from Sutter and Alexandrescu (must be IMHO)
- Efficient C ++ / STL Series by Scott Meyers
- Exceptional C ++ Series from Herb Sutter
Above my head, one good common practice is to transfer heavy objects by reference, not copies. For example:
// Not a good idea, a whole other temporary copy of the (potentially big) vector will be created. int sum(std::vector<int> v) { // sum all values of v return sum; } // Better, vector is passed by constant reference int sum(const std::vector<int>& v) { // v is immutable ("read-only") in this context // sum all values of v. return sum; }
For a small object, such as a complex number or a two-dimensional (x, y) point, the function will most likely work faster with the object transferred by the copy.
When it comes to objects with a fixed size and average weight, it is not so clear if the function will work faster with a copy or link to the object. Only profiling will tell. Usually I just pass the const link (if the function doesn't need a local copy) and worry about it if the profiling tells me.
Some will say that you can embed methods in a small class without thinking. This can give you better performance at runtime, but it can also extend compilation time if you have a large number of attachments. If the class method is part of the library API, it is best not to include it, no matter how small it is. This is due to the fact that the implementation of built-in functions should be visible to other modules / classes. If you change something in this built-in function / method, then the other modules that reference it must be compiled.
When I first started programming, I would still try to optimize everything (it was an electrical engineer in me). What a waste of time!
If you are in embedded systems, then everything changes, and you cannot take memory for granted. But this is another whole can of worms.