I'm getting poor performance when formatting text in an rtb:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button Click="ApplyFormatClick">ApplyFormat</Button>
<TextBlock x:Name="Time"/>
</StackPanel>
<RichTextBox x:Name="Rtb" Grid.Row="1">
<RichTextBox.Document>
<FlowDocument>
<Paragraph>
<Run>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</Run>
</Paragraph>
</FlowDocument>
</RichTextBox.Document>
</RichTextBox>
</Grid>
Code behind:
private readonly SolidColorBrush _blueBrush = Brushes.Blue;
private void ApplyFormatClick(object sender, RoutedEventArgs e)
{
Stopwatch stopwatch = Stopwatch.StartNew();
FlowDocument doc = Rtb.Document;
TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd);
range.ClearAllProperties();
int i = 0;
while (true)
{
TextPointer p1 = range.Start.GetPositionAtOffset(i);
i++;
TextPointer p2 = range.Start.GetPositionAtOffset(i);
if (p2 == null)
break;
TextRange tempRange = new TextRange(p1, p2);
tempRange.ApplyPropertyValue(TextElement.ForegroundProperty, _blueBrush);
tempRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
i++;
}
Time.Text = "Formatting took: " + stopwatch.ElapsedMilliseconds + " ms, number of characters: " + range.Text.Length;
}
Applying the formatting takes over a second and when profiling it the culprits are:
tempRange.ApplyPropertyValue(TextElement.ForegroundProperty, _blueBrush);
tempRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
The profiler results are pretty opaque to me.
I have never used FlowDocument
and RichTextBox
before so I'm probably doing this very wrong.
The end result is meant to be something similar to the VS find replace that will highlight matches in the text based on an editable regex.
What can be done differently to speed this up? (Sample on Github)