ListBox に多くの項目を追加すると処理に時間がかかる - C#

ListBox に多くの項目を追加すると処理に時間がかかる現象の対策方法を紹介します。

概要

こちらの記事ではListBoxに要素を追加するコードを紹介しましたが。追加する項目数が増えると動作速度が低下します。この記事ではListBoxに多数の要素を高速に追加するコードを紹介します。

速度低下の原因

こちらの記事で紹介したコードは、1つの要素を追加するごとにListBoxの描画をするため追加する要素数が増えるに従い速度が遅くなります。

対策

ListBoxの再描画を抑制する
  • ListBox.BeginUpdate()
  • ListBox.EndUpdate()
メソッドを利用して要素を追加するたびにListBoxの再描画をしないようにします。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ListBoxDemo
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    //Add2ボタン
    private void button2_Click(object sender, EventArgs e)
    {
      int sel = listBox1.SelectedIndex;
      listBox1.Items.RemoveAt(sel);
    }

    //Add3ボタン
    private void button5_Click(object sender, EventArgs e)
    {
      listBox1.BeginUpdate();
      for (int i = 0; i < 100000; i++) {
        listBox1.Items.Add(string.Format("Line:{0:d}", i));
      }
      listBox1.EndUpdate();
    }

    //Clearボタン
    private void button6_Click(object sender, EventArgs e)
    {
      listBox1.Items.Clear();
    }
  }
}

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[Add2]ボタンを押してListBoxに要素を追加します。要素の追加ができたら、[Clear]ボタンを押しListBoxの要素をクリアし、その後[Add3]ボタンを押してListBoxに要素を追加します。要素追加時の速度を比べると、Add2ボタンを押して要素を追加した時より、Add3ボタンを押して要素を追加したほうが処理時間が短いことがわかります。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2020-05-23
作成日: 2013-01-25
iPentec all rights reserverd.