Performance implications of using a variable versus a magic number
- by Nathan
I'm often confused by this. I've always been taught to name numbers I use often using variables or constants, but if it reduces the efficiency of the program, should I still do it? Heres an example:
private int CenterText(Font font, PrintPageEventArgs e, string text)
{
int recieptCenter = 125;
int stringLength = Convert.ToInt32(e.Graphics.MeasureString(text, font));
return recieptCenter - stringLength / 2;
}
The above code is using named variables, but runs slower then this code:
private int CenterText(Font font, PrintPageEventArgs e, string text)
{
return 125 - Convert.ToInt32(e.Graphics.MeasureString(text, font) / 2);
}
In this example, the difference in execution time is minimal, but what about in larger blocks of code?