How do I write more efficient code?
Obviously it is important for any programmer to make his/her code as efficient as possible. But are there any guidelines that anyone can give?
So for instance, will my code be more efficient if I do the following?
Use fewer variables
Use fewer lines
For Instance, is:
Code:
for (int i=0;x;i++)
{
//do stuff to x
}
better than:
Code:
for (int i=0;;i++)
{
//do stuff to x
if(x==0)
break;
}
Make many functions dedicated to simple tasks to avoid code repetition
So if I have:
Code:
if (x>y)
{
z=1;
}
else
{
z=0;
}
more than once is it always better to do:
Code:
z=compare(x,y);
//where compare() is:
int compare(int x,int y)
{
if (x>y)
{
return 1;
}
return 0;
}
Is it dependent upon the intelligence of your compiler (I use MSVC++)?
So for instance will:
Code:
s1 = s1 + s2 + s3 + s4;
and:
Code:
s1 += s2;
s1 += s3;
s1 += s4;
be recognised by the compiler as the same and therefore converted to the same machine code?
Can anyone gives any tips? Or point me to some info? I have tried googling but didn't get very much.