How to speed up access to the RichTextBox Lines property

CK CK 3788 
Created at  
834 0 0
Using a foreach loop will be substantially faster than a for loop when accessing the items in a RichTextBox's Lines property. For example, the following code loads a RichTextBox with 1000 lines of text and accesses each line from the Lines property. On a 333 MHz Pentium II machine, the for-loop code (ForLoopButton_Click) takes ~25 seconds and the foreach code (ForEachLoopButton_Click) takes ~0.01 seconds.

...
private void Form1_Load(object sender, System.EventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;

    StringBuilder Buffer = new StringBuilder("");

    for (int i = 1; i <= 1000; i++)
    {
        if (i > 1)
        {
            Buffer.Append(Environment.NewLine);
        }

        Buffer.Append("This is line number " + i.ToString());
    }

    TheRichTextBox.Text = Buffer.ToString();

    Cursor.Current = Cursors.Arrow;
}

private void ForLoopButton_Click(object sender, System.EventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;
    int Len = 0;

    int Start = Environment.TickCount;

    for (int i = 0; i < TheRichTextBox.Lines.Length; i++)
    {
        Len += TheRichTextBox.Lines[i].Length;
    }

    int ElapsedTime = Environment.TickCount - Start;

    ResultsTextBox.Clear();

    ResultsTextBox.Text = "for loop Elapsed time = " + ((double) ElapsedTime / (double) 1000.0).ToString() + " seconds Result = " + Len.ToString();

    Cursor.Current = Cursors.Arrow;
}

private void ForEachLoopButton_Click(object sender, System.EventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;
    int Len = 0;

    int Start = Environment.TickCount;

    foreach (String Line in TheRichTextBox.Lines)
    {
        Len += Line.Length;
    }

    int ElapsedTime = Environment.TickCount - Start;

    ResultsTextBox.Clear();

    ResultsTextBox.Text = "foreach loop Elapsed time = " + ((double) ElapsedTime / (double) 1000.0).ToString() + " seconds Result = " + Len.ToString();

    Cursor.Current = Cursors.Arrow;
}
...

Tags 2005 Welcome Page C# Environment StringBuilder Facebook X
Comments 0
Similar posts
  1. The best way to enable and disable buttons, menu items and toolbar buttons
    668
  2. How to restrict a program to a single instance
    733
  3. Graphics in C# - Irregular Forms
    914
  4. Extracting the Country from IP Address
    471
  5. How to print character in C# by ASCII code
    480
  6. How To Print Text In C#
    457
  7. How to send binary data through C# CGI app?
    999
  8. Calling Your Main Thread From A Worker Thread In C#
    551
  9. How To Read And Write A Cookie
    365
  10. Using C# With Cookies
    633
  11. To load image from file
    457
  12. How to convert bitmap image to jpeg image ?
    362
  13. How to resize and save PNG or Jpeg Image file ?
    638
  14. How to convert text string to integer ?
    616
  15. How to convert integer to text string ?
    701
  16. How to get process id in C# like windows task manager ?
    872
  17. How To Check If Your Printer Is Connected Using C#
    1,027
  18. How to download/grap web pages or XML document at internet website in Delphi XE?
    880
  1. How to send text/html based email in UTF-8 with TIdSMTP, TIdMessage VCL
    1,084
  2. How to encode subject content when sending mail with TIdMessage ?
    1,077
  3. Base64 Encoding/Decoding function for Delphi
    1,176
  4. How to send email by TIdSMTP VCL ?
    1,023
  5. How to return exit code such as exit() function in C/C++ ?
    670
  6. How to get parameter string ?
    1,251
  7. Save TBitmap image to Jpeg format image in Delphi
    717
  8. How to get screen resolution in case of using multiple monitors ?
    454
  9. How to turn off monitor ?
    435
  10. Find File at certain directory in Delphi
    441
  11. Sending email messages in .Net
    1,041
  12. Delphi for .Net Code Folding keyboard shortcuts
    531
  13. How to encrypt a string
    469
  14. Creating thumbnail images
    867
  15. Technology sharing related with software development. Specially content will be focused to programming language, and embedded systems.
    855
  16. Window flashing
    380
  17. How to use TTF Font Without Installing
    1,124
  18. How to show window contents while dragging
    461
  19. How to save text from Clipboard to a file
    573
  20. How to send char as message to another application
    549
  21. How to restrict mouse movement
    415
  22. List Devices (LPT, COM ports, ...)
    479
  23. How to know whether the font is TrueTypeFont or not
    380
  24. How to track a user's idle time
    594
  25. How to remove your application from TaskBar
    659
  26. How to play sounds on the PC Speaker ?
    533
  27. How to install an INF file using Delphi ?
    469
  28. How to determine the output of a console application ?
    457
  29. Get text from the control at pos x,y on screen
    476
  30. Get dimensions of usable space on monitor (work area)
    492
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,240
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    107
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    208
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    116
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    230
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233