はじめに
Windows フォームのテキストボックス(.NET Framework の Windows Forms コントロール System.Windows.Forms.TextBox)で複数行の長い文章(文字列)を表示させるとき、WordWrap プロパティを false に設定すると、時間を大幅に短縮できることがあります。
比較結果
データには、日本郵便株式会社提供の「郵便番号データ.csv 全国一括版 」(KEN_ALL.CSV) を利用させていただきました。
- ・WordWrap = false
- 平均 0.168087467 秒
{0.1545456, 0.172627, 0.17709} - ・WordWrap = true (既定)
- 平均 14.61888617 秒
{14.4527749, 14.609843, 14.7940406}
検証したコード
Windows Forms アプリケーション(.NET Framework 4.7.2)で作成しています。
Form1.cs
using System;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
// textBox1 が、測定対象のテキストボックス
public Form1()
{
InitializeComponent();
textBox1.MaxLength = 0;
textBox1.Multiline = true;
textBox1.ScrollBars = ScrollBars.Both;
textBox1.WordWrap = false; // or comment out
}
// 読み込みボタン (button1) 押下
private void Button1_Click(object sender, EventArgs e)
{
var text = System.IO.File.ReadAllText(@"..<path>..\KEN_ALL.CSV", System.Text.Encoding.GetEncoding(932));
var data = text + text + text;
var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
textBox1.Text = data;
Application.DoEvents();
stopWatch.Stop();
System.Windows.Forms.MessageBox.Show(stopWatch.Elapsed.ToString());
}
}
}
おわりに
WordWrapプロパティをfalseにすることで、1行が横幅を超えると横スクロールが必要になってしまいますが、処理時間はかなり短縮されるので、ログ表示をしたりテキストエディタのようなアプリケーションでは検討に値すると思います。