Reputation: 1005
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
}
.
.
.
Upvotes: 0
Views: 1174
Reputation: 57932
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.
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.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).
Upvotes: 1