-3

I'm trying to optimize my code. I've heard that it's better not to use local variables and to reduce the number of function parameters, so currently the structure of my program looks like this:

using namespace std;    
const string UPLOAD_LOCATION = "/uploads";    
const int value = 100;
const int type = 0;
const int max_value = 255;    
string var1, var2, var3;

void func1();
void func2();
void func4();

int main(int argc, char *argv[])
{
    func1();
    func2();
}

void func1()
{
  //do something
}

void func2()
{
  func4();
  //do something
}

void func4()
{
  //do something
}

Would it be more efficient if var1, var2 and var3 were local variables in main function, so I'd pass them as arguments to the functions? I mean something like this:

using namespace std;    
const string UPLOAD_LOCATION = "/uploads"; 

void func1();
void func2();
void func4();

int main(int argc, char *argv[])
{
    const int value = 100;
    const int type = 0;
    const int max_value = 255;    
    string var1, var2, var3;

    var1 = func1(var2, value, type, max_value);
    var3 = func2(var2);
}

string func1(string &var2)
{
  //do something
}

void func2(string &var2)
{
  func4(var2);
  //do something
}

void func4(string &var2)
{
  //do something
}

If yes, is it better to pass them by reference or by value? For example lets say the function stores the result in string s, then which choice should I make:

a) void func( string in, string &result )    

or

b) string func( string in )
nena
  • 147
  • 1
  • 3
  • 11
  • 1
    Do you want to hear opinions? Otherwise just benchmark it yourself. That includes your OS and your compiler. Talking about performance without benchmarking is useless. – usr1234567 Jul 24 '14 at 13:56
  • 3
    Compilers are good at optimizing. The only way to say something meaningful about efficiency is writing both, compiling it with optimization enabled and then measure the result! – Baum mit Augen Jul 24 '14 at 13:56
  • 2
    You should benchmark, and you might not care. – Basile Starynkevitch Jul 24 '14 at 13:56
  • You've asked _too_ many questions and _every_ of them is broad. – Lol4t0 Jul 24 '14 at 14:00
  • 6
    "I've heard that it's better not to use local variables and to reduce the number of function parameters" from whom? Never listen to them again. – Neil Kirk Jul 24 '14 at 14:01
  • 1
    @JamesKanze Using globals is usually faster because they have a fixed position that the compiler can hard code for vs. a stack or heap variable that must be accessed thru a pointer (stack + offset or just direct pointer.) That said, it only saves a few bytes of instructions, may not be measurably faster, probably creates threading issues, and is generally considered bad style. – Khouri Giordano Jul 24 '14 at 14:05
  • 1
    @KhouriGiordano, compiler abilities in globals optimization are restricted: compiler cannot completely replace globals with registers, as they can be accessed from the other module, so it has to sync globals with memory before any crossmodule function call. – Lol4t0 Jul 24 '14 at 14:09
  • @Lol4t0 Sorry about asking so many questions, but since all of them are related to the same code I thought it's better to do it like this. Should I split it in three different questions? – nena Jul 24 '14 at 14:13
  • @KhouriGiordano No stack is usually faster because compiler can make more optimizations. – Neil Kirk Jul 24 '14 at 14:14
  • 1
    BTW, it is not easy to benchmark. I mean you need to execute each case thousands of times in a loop to get a measurable result. – drescherjm Jul 24 '14 at 14:15
  • @nena, actually most of the questions have already been asked there. You should split you question in your mind and then search subquestions here. – Lol4t0 Jul 24 '14 at 14:16
  • 3
    To understand micro-optimization, including commonly believed fallacies regarding the state of compiler optimization, and micro-optimization on present day systems, I would suggest reading [Source Code Optimization](http://www.fefe.de/source-code-optimization.pdf) ("Know your compiler") by [Felix von Leitner](http://www.fefe.de/), Eric Lippert's [Which is faster](http://ericlippert.com/2012/12/17/performance-rant/) "performance rant" and [The sad tragedy of micro-optimization theater](http://blog.codinghorror.com/the-sad-tragedy-of-micro-optimization-theater/) by Jeff Atwood. – mctylr Jul 24 '14 at 14:28
  • @KhouriGiordano Using globals is almost always slower on a modern machine, because they require a 32 bit constant address, rather than just a small offset from the frame pointer. (Many modern machines don't even have an instruction for direct memory access, and on those that do, it's rarely faster than based addressing.) – James Kanze Jul 24 '14 at 14:39
  • @NeilKirk Addressing through the frame pointer is usually faster than direct addressing, at least on most machines. (On a Sparc, for example, to access a global variable, you need a machine instruction to set up a base pointer to it, then you use the same instruction that you use to access through the frame pointer. On earlier Intel---I've not looked lately---the first addition was free; it takes place in parallel with other parts of the instruction decoding, and is _always_ present.) Local variables also tend to have better locality. – James Kanze Jul 24 '14 at 14:43
  • @JamesKanze I think you misunderstood my comment, I should have said "No, stack is usually faster" :) – Neil Kirk Jul 24 '14 at 14:47

4 Answers4

10

Do not make all your locals and parameters globals

No...just...stop.

Make your code understandable to yourself and other human beings. That should be your goal. That's what you can do that a computer cannot.

Let your compiler optimize things. That's what it can do way better than you. If things will run much faster with certain variables not put on the stack, your compiler should be quite capable of recognizing that.

If you want more specific design goals when creating classes and methods, try to minimize coupling and maximize cohesion. Often times, you will even find that you get efficiency for free when you do this.

If the result isn't fast enough to meet requirements, with your compiler's optimization settings full out, only then should you really concern yourself with hand-optimizing. In this case, you get a profiler and actually measure what parts of your code are wasting the most time, and fix those parts. That way you don't stumble around punching at nothing like a blind boxer.

T.E.D.
  • 44,016
  • 10
  • 73
  • 134
3

I'll take a stab at a couple of the questions

In the past it has always been better to pass by reference then value if you are not worried about the method you are calling modifying the value. IF you pass by value it has to do a copy construct, if you pass by reference it's just passing a pointer.

That said, C++ 11 is smarter and more efficient with the pass by value. So this is no longer a hard and fast rule. See this article for more info.

IN reference to your last question about having your value returned in as a parameter or the output of the method. This article is good at pointing out the pros and cons

Community
  • 1
  • 1
Brian S
  • 3,096
  • 37
  • 55
1

Premature optimization is root of all evil

First and foremost make your program readable. Then make it work and only then and only if necessary optimize it. First optimize it on algorithm level, then run through profiler, find where your program spends most of the time and optimize that.

To your question:

void func( string in, string &result );
void func( string in );

Let's look which way is more readable to call such a function:

string str;
func( "foobar", str );

vs:

string str = func( "foobar" );

Can you guess at least in which case it is easier to understand that str is modified after func() call? As for optimization C++ committee did a great job to make more natural way of passing and returning values to/from functions as efficient as their less readable equivalent. So stop worry about what does not really matter and focus on what is necessary to write a good program.

Slava
  • 43,454
  • 1
  • 47
  • 90
0

I'm trying to optimize my code. I've heard that it's better not to use local variables and to reduce the number of function parameters

It is better to not use global state (variables and objects) and to reduce number of function parameters (where this makes sense). Your confusion here seems to come from the idea that this "it's better" means "it's better for efficiency reasons".

You will not optimize the speed (or memory footprint) of your code by reducing global state and number of function parameters. Instead, you will compartimentalize functionality and reduce interependency of various modules in your application making it easier to read, maintain and extend.

Would it be more efficient if var1, var2 and var3 were local variables in main function, so I'd pass them as arguments to the functions?

No. This has nothing to do with efficiency (but your second example of the same code is much easier to read).

utnapistim
  • 26,809
  • 3
  • 46
  • 82