views:

83

answers:

1

I have performance issues in this code segment which I think is caused by the "new Font".

Will it be faster if fonts are static/global ?

if (row.StartsWith(TILD_BEGIN))  
{
    rtbTrace.SelectionColor = Color.Maroon; 
    rtbTrace.SelectionFont = new Font(myFont, (float)8.25, FontStyle.Regular);

    if (row.StartsWith(BEGIN) ) 
        rtbTrace.AppendText(Environment.NewLine + row + Environment.NewLine);
    else
        rtbTrace.AppendText(Environment.NewLine + row.Substring(1) 
            + Environment.NewLine);

    continue;
}

if (row.StartsWith(EXCL_BEGIN))
{
    -- similar block
}

if (row.StartsWith(DLR_BEGIN))
{
    -- similar block
}
.
.
.
+1  A: 

If you can avoid 'new' every time you do this operation, then it will be faster. So if you repeat this operation many times and the font does not change, you should refactor the creation of the font into a different location.

  • If your code is in a loop (it looks this way, as you have continue; in it, then you can 'new' the font once just outside the loop so it is initialised once instead of once-per-loop-iteration.
  • If the code is in a method that is called many times, then you can add a Font member variable to your class and 'new' it with a default value, or in the constructor or an initialisation method.
  • If you create and destroy many instances of the class that is doing this work, then you can make the font a static member so it is only initialised once for each execution of your application - again you can initialise it with a default value, or in a static constructor or initialiser method.

(Alternatively, in the last two cases, if there are times when you might not need to use the font at all, then you can initialise the font variable to null, and then do a lazy "just in time" creation by checking if (font == null) font = new Font(...); just before any code that needs to use it, so it is only created once, but it isn't created at all if not needed).

Jason Williams