Which C++ code is more efficient? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
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 )

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.

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

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.

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).

Related

Minimalizing variable's scope in C++

I am programming for a while now and I've started trying to improve my code. Since I really hate creating bazillion of variables that are used only once in long function, is it good practice to shorten variable scope by using brackets?
i.e.
instead writing:
void fcn()
{
int var1;
// some part of fcn
// use of var1;
// rest of fcn
}
write:
void fcn()
{
// some part of fcn
{
int var1;
// use of var100;
}
// rest of fcn
}
Yes it is indeed a good idea to keep the scope of variables as tight as possible.
In your case, unless you are absolutely certain that your code using var1 will only ever be used in fcn (and if my experience is anything to go by, I tend to misjudge that), you could split that code out to a separate function. Your program will scale better that way, and testing will also be simpler. Else, use scope blocks as you currently do.
There are certainly context in which this approach is a good practice.
It is so wide spreaded around 'if/range for/while/case' statements that explicit initializer in those statement were added in C++17 and C++20.
You shouldn't write int var1; anywhere.
Firstly var1 is a terrible name.
Secondly you now have the potential for undefined behaviour, if any code path can read var1 before it is assigned.
Prefer
int meaningfulName = initialValue;
Or even better
const int meaningfulName = value;
Having done that, the scopes you are choosing between are more restricted. If there is still a choice, prefer the narrowest scope possible.

Confused regarding this statement about "function call by reference."

What I'm confused about is whether the question is asking about passing arguments to functions as references (as opposed to "Call by Value") or about how we can set a pointer to point to a function.
The exact question is:
"Explain the function call by reference giving a suitable example in support of your answer."
The way it's termed makes it feel like it's asking about the latter. In my head, it seems as if it's asking how a function is called by reference, i.e, using a pointer.
C++ for what I'm talking about: int (*ptr)(int, int);
Which can later be assigned to a function like int max(int a, int b);
I know this is a bit of an odd post for Stack since it's more of an English question, but it's the only place I could think to ask.
EDIT: A lot of people are asking what I mean by the second thing. Since I'm new to the concept, I'll just copy - paste what my textbook gives as an example: (Sorry for the terrible formatting, sorry!)
main() {
int max(int a, int b){...}; //Your typical maximum function
int (*ptr)(int, int);
ptr = max;
//Then if you want to run the program
m = (*ptr)(2, 5);
cout << m; //Outputs 5
}

What is the difference between constant declaring Global or declaring inside a function where it is used [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i am declaring a constant (a large structure constant containing string) inside a function and it is used only inside this function.
will it have any execution time impact on my program? '
They will be created every time the function is called (take more time) or only once and the reference will be used through out its life.
If i declare the constant outside the function (global) will it be faster in execution ?
Actually, declaring variables inside of a function is a great practice. If that variable is only to be used inside of that function of course. There won't be any performance differences between the two methods, but making the constant global may require a more creative naming scheme while the one inside the function can be generic. It is only being used inside of that function, after all.
static struct can help you setting it up once and be done with it. This will be coming from data segment and initialise during at the startup. A raw and dirty code below, but will give you some intuition.
#include <stdio.h>
struct A {
int a;
int b;
};
void func(void)
{
static struct A a = {5,3};
printf("FUNC: A.a: %d\n", a.a);
}
int main(int argc, char **argv)
{
static struct A a = {6,4};
printf("MAIN: A.a: %d\n", a.a);
func();
return 0;
}
I would personally move it out of the function body if any other related functions use the variable, as long as you're using namespaces.
Also if its a true constant, I believe you can declare a struct static constexpr, which means that it won't be allocated on the stack every time the function is called (static), even if you declare it inside the function body. It also means that where it can be used at compile time, it will be (constexpr).
#include <iostream>
namespace Test{
struct Test {
char name[11];
int a;
int b;
};
static constexpr Test TEST_CONSTEXPR = {
"test value",
5,
6
};
}
int main()
{
std::cout << Test::TEST_CONSTEXPR.name << std::endl;
std::cin.get();
return 0;
}
In Ada this is compiler dependent. (As performance usually is.)
As "constants" are not compile-time static, a compiler may do the safe thing and evaluate the initialising expression every time the constant is declared.
If it really matters, measure what your compiler does.

C++ Functions returnings vs Functions setting a pointer

I would like to know the difference between functions that return a value and functions that set a value to a pointer, for example:
Pointer:
int myVal;
ptr_multiply(5, 5, &myVal);
cout << myVal << endl; //Output: 25
Return:
int myVal = rtn_multiply(5, 5);
cout << myVal << endl; //Output: 25
My question focuses in what method to choose when creating functions and why, as well as what advantages/disadvantages can we find in each of them.
Readability is the main reason functions typically return what you expect them to return. However, as this is highly subjective, I suggest you strive for consistency within your project.
When you want a function to return multiple things and not group them all together in a structure just so you can return them, an alternative is to return them in output parameters.
If you have big pieces of data to return, then you might come across to performance-bottlenceks. The reason is that that the returning value must be copied.
But in the most cases you don't have to worry about that, because modern compilers are capable of auto-inline things like that.
Side note: In C++ try to avoid naked pointers as much as possible (use references, smart-pointers)
One advantage to use the "pointer" method is that you can have multiple "return" values by passing in non-const references or pointers. For example:
int output1;
int output2;
get_values("input", &output1, &output2)
You can return a success/failure:
int v = -1;
if(ToInt("wibble",&v)){
// do something with v
}
Would fail as "wibble" can't be converted to an int.
The other useful thing is that the function doesn't have to change v:
int v = previousValue;
UpdateIfNewValueFound( &v )
Return the value. With modern compilers there should be almost no difference in performance between the two, but returning the value has several advantages:
By definition, it's what a function should do (i.e. a function maps from a domain to a codomain).
It's self-documenting; if I'm using an unfamiliar API, unless there is good documentation, it can get confusing what is input/output if values are returned in the parameter set. With a returned value there is no ambiguity, and requires less documenting.
It's easier to use - can half the number of lines needed! Compare
int r = f();
to
int r;
f(&r);
It could make you a better programmer; you have to put more effort into returning multiple values from a function (e.g. via a struct or pair, as opposed to adding another parameter). If you find you need to do this often, the additional effort may force you to think more carefully about your code design - it's usually better for a function to just do/return one thing.
Another difference is stack or heap.
A return-value lies on top of the stack. The pointer-variant lies in heap.
For instance (sensless recursive code to demonstrate return on stack):
typedef std::array<int,1000> KByte;
KByte tmp;
KByte f(int nr) {
if (nr == 1) { tmp[nr]=nr; return tmp; }
else { tmp[nr]=nr; return f(nr-1); };
}
void f2(int nr, KByte& ret) {
if (nr == 1) { ret[1]=1; }
else { ret[nr]=nr; f2( nr-1, ret ); }
};
Calling
KByte t = f(999); /* Stack error */
shoud give you an stack-size error, since 1000 KByte (1GB) on the stack is to much.
Calling
KByte t2;
f2( 999, t2 );
should work without stack problem. (It also uses recursion depth 1000, but does not lie the return value on the stack.

Pointer vs Return [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Which is faster when assigning a variable via a method, to return a variable, or to point to a variable?
Case 1:
Function Declaration
void foo(int* number)
{
*number = 5;
}
Usage
int main()
{
int number;
function(&number);
cout << "Number: " << number;
}
Case 2:
Function Declaration
int foo()
{
int number = 5;
return number;
}
Usage
int main()
{
int number;
number = function();
cout << "Number: " << number;
}
PS: In case 2, I created a variable and returned it instantly. I know this doesn't make sense, but this is the closest example I can find for the situation I'm dealing with, since I'm initializing an actual object, which requires creating the object first, editing it, then returning it
It depends on the cost of copying the variable. For primitive types, return a value.
For more complex types consider passing in a reference, or take a look at the C++11 move semantics.
One benefit of using output parameters (Case 1) is it gives you the ability to have a function 'return' multiple values:
void foo (int* x, int* y)
{
*x = 5;
*y = 4;
}
But like everyone said in the comments, this doesn't matter in C++ as much as C.
Generally returns are far more readable and make your program's logic well defined and
easy to follow. In C++, stick to returns or references.
Typically, you should choose which to use on your needs rather than on performance.
Do you have multiple outputs? -> Use pointers
Is an input going to be an output -> Might as well use pointers
It's more difficult with these two scenarios to return a variable.
Other than that, performance-wise, it's only nice to use a variable when the variable is super complex, that way, you're only passing in a pointer instead of that super complex object. But any performance gain is negligible other than that.