Performance implications of using a variable versus a magic number
        Posted  
        
            by 
                Nathan
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Nathan
        
        
        
        Published on 2013-10-18T18:58:10Z
        Indexed on 
            2013/10/18
            21:55 UTC
        
        
        Read the original article
        Hit count: 216
        
c#
|magic-numbers
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?
© Stack Overflow or respective owner