Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slow formatting of RichTextBox

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)

like image 501
Johan Larsson Avatar asked Jul 25 '13 08:07

Johan Larsson


2 Answers

Suggestion will be to manually construct your FlowDocument with the new formating (you can check the MSDN Magazine August 2007: WPF Flexible Content Display With Flow Documents; or the most recent MSDN article Flow Document Overview ), which will improve the performance dramatically, e.g. use your example if do it manually as below, on my machine it will get the result in 52 ms, where as using ApplyPropertyValue will take 1266 ms:

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);
    Paragraph para = new Paragraph();
    string rangetem = range.Text;
    range.ClearAllProperties();

    for(int i=0; i<rangetem.Count();i+=2)
    {
        Span s = new Span() { Foreground = _blueBrush };
        Bold b = new Bold();
        s.Inlines.Add(rangetem[i].ToString());
        b.Inlines.Add(s);
        para.Inlines.Add(b);
        if(i+1<rangetem.Count())
        {
            para.Inlines.Add(rangetem[i + 1].ToString());
        }
    }
    doc.Blocks.Clear();
    doc.Blocks.Add(para);

    Time.Text = "Formatting took: " + stopwatch.ElapsedMilliseconds + " ms, number of characters: " + range.Text.Length;
}
like image 61
Bolu Avatar answered Oct 15 '22 20:10

Bolu


If back functionality is not needed from the RichTextBox you can squeeze a bit more performance by setting IsUndoEnabled to false

<RichTextBox IsUndoEnabled="False">
like image 7
Moon Waxing Avatar answered Oct 15 '22 18:10

Moon Waxing