13

I have a performance problem. I create 100 new buttons and I want to assign an Click Event Handler. I execute this code for about 100 times:

Buttons[i].Button.Click += new System.EventHandler(Button_Click);

It takes about 2sec to complete. I have a lot of other event assignments in the same function, but they all take only some millisecond to execute. So I have transformed my code in

Buttons[i].Button.MouseUp += new System.Windows.Forms.MouseEventHandler(Button_Click);

Now the code is fast (some millisecond, like the others). Obviously I have modified the parameters of the function "Button_click" to fit the new event requirements, but no other changes were made.

I am wondering why this could happen. Is EventHandler that slow? Or am I doing something wrong? Or is there a best practice?

I am using VC2010 with C#, using .NET 4 in a Windows Form application.

EDIT:

Now I have "minified" my code and I put it there:

            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            Button b;
            for(n=0;n<100;n++)
            {
                b = new Button();
                b.Location = new System.Drawing.Point(100, 0);
                b.Name = "btnGrid";
                b.Size = new System.Drawing.Size(50, 50);
                b.Text = b.Name;
                b.UseVisualStyleBackColor = true;
                b.Visible = false;
                b.Text = "..";
                b.Click += new EventHandler(this.Button_Click);
                //b.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Button_ClickUP);
            }
            stopWatch.Stop();

            TimeSpan ts = stopWatch.Elapsed;
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            Log(elapsedTime, Color.Purple);

Button_Click and Button_Click are:

    private void Button_Click(object sender, EventArgs e)
    {            
    }

    private void Button_ClickUP(object sender, MouseEventArgs e)
    {
    }

I put this code in a button and the "Log" function display the result in a memo. When I enable "Click" the result is 01.05 sec, but when I enable "MouseUp" the result is 00.00.

Difference -> ONE SECOND!

why!?

== EDIT ==

I use .NET Framework 4. VS2010. Win XP. I found this: if I use .NET 3.5 or lower the speed changes: 0.5 sec. An Half. If I compile in debug or release mode it doesn't change.

If I use the executable without the debugger is blazing fast.

So I change my question: is .NET 4 slower then .NET 3? Why the Release mode works differently compared to the stand alone version?

Many thanks.

Redax
  • 9,231
  • 6
  • 31
  • 39
  • 6
    I struggle to imagine a situation where 100 buttons on a single form could possibly be good design... – Cody Gray - on strike May 10 '11 at 14:12
  • 7
    @CodyGray: Minesweeper :) – MPelletier May 10 '11 at 14:18
  • @CodyGray How many buttons on your keyboard? ;) –  May 10 '11 at 14:24
  • 3
    @JonB: Too damn many; it seems I'm always hitting the wrong one. – Cody Gray - on strike May 10 '11 at 14:26
  • 1
    How have you determined that this line is what is taking your two seconds? It strikes me as highly unlikely that, over 100 iterations, adding a Click handler vs. adding a MouseUp handler could have such a dramatic performance difference. Can you put together a minimal console application that reproduces the behavior? – Dan Bryant May 10 '11 at 14:28
  • 1
    Please let us know how you eventually fix this, I'm curious and if it's as described it'll be important to know. –  May 11 '11 at 09:11
  • Yes! I have a kind of keyboard. And I have to switch between 5 pages of keyboards. I have tested with a timer just outside the iteration. if I disable that line, the code is a lot faster. – Redax May 12 '11 at 08:21
  • I modified the code you've got there so that there are 100,000 buttons, on my machine the code completes for both event types in ~1.35 seconds. You must have something else. Have you tried that code in an otherwise completely blank form? –  May 12 '11 at 09:43
  • 1
    I turned off IntelliTrace, and voila. Speedup! – Wolf5 Jun 12 '15 at 11:51

4 Answers4

5

The code ".Click += ..." is transformed into ".add_Click( ... )". The "add_Click" method can have some logic checks.

You can little-bit speed up with no recreation of delegate:

EventHandler clickHandler = this.Button_Click;
foreach(Button btn in GetButtons()) {
   btn.Click += clicHandler;
}

EDIT:

Are you sure, the bottleneck is the attaching the handlers? I tried the for loop (100 loops) with attaching the eventhandler to Click event and I get this results:

/* only creation the button and attaching the handler */
button1_Click - A: 0 ms
button1_Click - B: 0 ms
button1_Click - A: 1 ms
button1_Click - B: 0 ms
button1_Click - A: 0 ms
button1_Click - B: 0 ms

/* creation the button, attaching the handler and add to the panel */
button2_Click - A: 223 ms
button2_Click - B: 202 ms
button2_Click - A: 208 ms
button2_Click - B: 201 ms
button2_Click - A: 204 ms
button2_Click - B: 230 ms

The source code:

    void button_Click(object sender, EventArgs e) {
        // do nothing
    }

    private void button1_Click(object sender, EventArgs e) {
        const int MAX_BUTTONS = 100;
        var stopWatch = new System.Diagnostics.Stopwatch();
        stopWatch.Start();
        for (int i = 0; i < MAX_BUTTONS; i++) {
            var button = new Button();
            button.Click += new EventHandler(button_Click);
        }
        stopWatch.Stop();
        System.Diagnostics.Debug.WriteLine(string.Format("button1_Click - A: {0} ms", stopWatch.ElapsedMilliseconds));

        stopWatch.Reset();
        stopWatch.Start();
        EventHandler clickHandler = this.button_Click;
        for (int i = 0; i < MAX_BUTTONS; i++) {
            var button = new Button();
            button.Click += clickHandler;
        }
        stopWatch.Stop();
        System.Diagnostics.Debug.WriteLine(string.Format("button1_Click - B: {0} ms", stopWatch.ElapsedMilliseconds));
    }

    private void button2_Click(object sender, EventArgs e) {
        const int MAX_BUTTONS = 100;

        var stopWatch = new System.Diagnostics.Stopwatch();

        this.panel1.Controls.Clear();
        stopWatch.Start();
        for (int i = 0; i < MAX_BUTTONS; i++) {
            var button = new Button();
            button.Click += new EventHandler(button_Click);
            this.panel1.Controls.Add(button);
        }
        stopWatch.Stop();
        System.Diagnostics.Debug.WriteLine(string.Format("button2_Click - A: {0} ms", stopWatch.ElapsedMilliseconds));

        stopWatch.Reset();

        this.panel1.Controls.Clear();
        stopWatch.Start();
        EventHandler clickHandler = this.button_Click;
        for (int i = 0; i < MAX_BUTTONS; i++) {
            var button = new Button();
            button.Click += clickHandler;
            this.panel1.Controls.Add(button);
        }
        stopWatch.Stop();
        System.Diagnostics.Debug.WriteLine(string.Format("button2_Click - B: {0} ms", stopWatch.ElapsedMilliseconds));
    }

EDIT 2: I tried compare time spent with attaching Click handler vs. attaching MouseUp handler. It does not seems, the attaching MouseUp event is faster than Click event.

I think the problem will be somewhere else. Don't GC collect during your loop? Or don't you do something else there?

Results:

button1_Click - Click_A: 6 ms
button1_Click - Click_B: 6 ms
button1_Click - MouseUp_A: 15 ms
button1_Click - MousUp_B: 7 ms

button1_Click - Click_A: 16 ms
button1_Click - Click_B: 7 ms
button1_Click - MouseUp_A: 16 ms
button1_Click - MousUp_B: 10 ms

button1_Click - Click_A: 14 ms
button1_Click - Click_B: 19 ms
button1_Click - MouseUp_A: 27 ms
button1_Click - MousUp_B: 5 ms

button1_Click - Click_A: 17 ms
button1_Click - Click_B: 17 ms
button1_Click - MouseUp_A: 24 ms
button1_Click - MousUp_B: 8 ms

button1_Click - Click_A: 6 ms
button1_Click - Click_B: 5 ms
button1_Click - MouseUp_A: 14 ms
button1_Click - MousUp_B: 7 ms

button1_Click - Click_A: 14 ms
button1_Click - Click_B: 9 ms
button1_Click - MouseUp_A: 15 ms
button1_Click - MousUp_B: 7 ms

Code:

    private void button1_Click(object sender, EventArgs e) {
        const int MAX_BUTTONS = 1000;
        var stopWatch = new System.Diagnostics.Stopwatch();

        stopWatch.Start();
        for (int i = 0; i < MAX_BUTTONS; i++) {
            var button = new Button();
            button.Click += new EventHandler(button_Click);
        }
        stopWatch.Stop();
        System.Diagnostics.Debug.WriteLine(string.Format("button1_Click - Click_A: {0} ms", stopWatch.ElapsedMilliseconds));

        stopWatch.Reset();
        stopWatch.Start();
        EventHandler clickHandler = this.button_Click;
        for (int i = 0; i < MAX_BUTTONS; i++) {
            var button = new Button();
            button.Click += clickHandler;
        }
        stopWatch.Stop();
        System.Diagnostics.Debug.WriteLine(string.Format("button1_Click - Click_B: {0} ms", stopWatch.ElapsedMilliseconds));

        stopWatch.Start();
        for (int i = 0; i < MAX_BUTTONS; i++) {
            var button = new Button();
            button.MouseUp += new MouseEventHandler(button_MouseUp);
        }
        stopWatch.Stop();
        System.Diagnostics.Debug.WriteLine(string.Format("button1_Click - MouseUp_A: {0} ms", stopWatch.ElapsedMilliseconds));

        stopWatch.Reset();
        stopWatch.Start();
        MouseEventHandler mouseUpHandler = this.button_MouseUp;
        for (int i = 0; i < MAX_BUTTONS; i++) {
            var button = new Button();
            button.MouseUp += mouseUpHandler;
        }
        stopWatch.Stop();
        System.Diagnostics.Debug.WriteLine(string.Format("button1_Click - MousUp_B: {0} ms", stopWatch.ElapsedMilliseconds));
    }

EDIT : The body of add_Click method (= Click += ...) is rough:

public void add_Click(EventHandler value) {
   this.Events.AddHandler(ClickEventIdentifier, value);
}

The MouseUp events will looks similar. At least both events using Events property for holding lists of delegates for events.

But if I tried several things I can not get the problems with the events as you wrote :(. Can you reproduce same behaviour on another computers?

TcKs
  • 25,849
  • 11
  • 66
  • 104
  • @TcKs: That was my first guess, too, but there is no logic check. Also, your suggestion doesn't speed up anything, because `btn.Click += this.Button_Click` is also valid. If it would speed up things, there would be no logical explanation why the assignments to `MouseUp` are faster. – Daniel Hilgarth May 10 '11 at 14:20
  • @Daniel Hilgart: I tried the for loop with 1000 buttons and the spent time is realy low (4ms - 15ms). Are you sure, the problem is with attaching events? – TcKs May 10 '11 at 14:46
  • @TcKs: No, I am not sure! But I never said that anyway. My answer tries to provide an explanation why adding an event handler to `Click` is slower than adding one to `MouseUp` *under the assumption that this really is the case!* – Daniel Hilgarth May 10 '11 at 14:49
  • @Daniel Hilgarth: Look at the second edit part. It didn't seems the attaching MouseUp event is faster than Click event. – TcKs May 10 '11 at 14:57
  • @TcKs: If you tried to implement the comparison I suggested in my answer, you need to change it, so that the second `for` loop uses the same buttons as the first. But as I already said: It is quite possible that the observations of the OP aren't side effect free, i.e. they are *wrong*. However, I based my answer on the assumption that they are correct. – Daniel Hilgarth May 10 '11 at 15:06
  • Your timing is very interesting: I have created a blank project and I have inserted your code and mine (as I edited on the top). In my computer the results are the same, but with MAX_BUTTONS = 100 I have a timing of about ONE sec. Maybe is my project? Or my default project options? or... i don't know. – Redax May 12 '11 at 09:13
  • @Redax: It's weird. Are you sure the CPU wasn't busy by another processes? – TcKs May 12 '11 at 12:48
  • @Redax: I tried your code. With the 100 buttons the result was "00:00:00.00". With the 1000 buttons the result was "00:00:00.03" (both multipletimes). Which version of .NET do you use? Or do you use Mono? – TcKs May 12 '11 at 12:55
  • @TcKs: I use .NET Framework 4. VS2010. Win XP. I found this: if I use .NET 3.5 or lower the speed changes: 0.5 sec. An Half. – Redax May 13 '11 at 07:16
  • I just looked up the decompiled funtions and methods and there arr no logic checks that would require so much time. The only thing i found that could take so much time is a loop that searches for the "EventClick" object, which should not be the source either as the button only uses one event. – quadroid Aug 27 '14 at 15:01
4

System.EventHandler is a delegate type and therefore doesn't do anything. This can't be the source of the difference in performance.
Adding a new Click handler and a new MouseUp event handler is the same internally. Both call Events.AddHandler.
In my eyes, the only difference can be, that either Click already has other event handlers attached and MouseUp hasn't or the other way around.
To check whether my assumption is correct, you could copy and paste the two code snippets and execute each twice and measure the duration for the first and second time.

If both runs for Click are slow and the second run for MouseUp is slow, the problem is, that there already are existing Click handlers and adding a handler when already one exists is slower than adding one when none exists.

If the first run for Click is slow and the second one is fast and both runs for MouseUp are fast, the problem is, that there are no existing Click handlers and adding a handler when already one exists is faster than adding one when none exists.

My answer assumes that the observations of the OP are side effect free. I didn't actually test whether his results are reproducible or plausible. My answer just wants to show that there really is nothing special to the Click event or System.EventHandler.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • Please let us know how you eventually fix this, I'm curious and if it's as described it'll be important to know. –  May 11 '11 at 08:55
  • @JonB: I guess your comment was meant to be posted to the question? – Daniel Hilgarth May 11 '11 at 09:09
  • 1
    God I'm not with it today, that's the second one. Time for coffee. –  May 11 '11 at 09:11
  • I'm curious to! I can say that there are no other event handlers. I tested also adding a second event handler to MouseUp: non speed down. – Redax May 12 '11 at 09:15
  • @Redax: Please check the performance measurements done by others. Normally, there shouldn't be a difference, i.e. you need to try to extract the difference between your code and theirs to learn, where it comes from. – Daniel Hilgarth May 12 '11 at 09:17
0

Try turning off IntelliTrace. Had the exact same symptoms. Blazing fast when not run under Visual Studio, but always added 30ms per btn.Click+= i made if running under Visual Studio.

So probably IntelliTrace that hooks into the Click events somehow for detailed debugging.

Wolf5
  • 16,600
  • 12
  • 59
  • 58
0

I tried this:-

  public partial class Form1 : Form
  {
    List<Button> buttonList = new List<Button>();
    public Form1()
    {
      for (int n = 0; n < 100; n++)
      {
        Button tempButt = new Button();
        tempButt.Top = n*5;
        tempButt.Left = n * 5;
        this.Controls.Add(tempButt);
        buttonList.Add(tempButt);
      }
      var stopwatch = new Stopwatch();
      stopwatch.Start();
      foreach (Button butt in buttonList)
      {
        butt.Click += new System.EventHandler(button1_Click);
      }
      stopwatch.Stop();
      Console.WriteLine(stopwatch.ElapsedMilliseconds);
    }

    private void button1_Click(object sender, EventArgs e)
    {
      Console.WriteLine("Cheese");
    }
  }

All the buttons appear and the events seem to fire correctly, the event handler assignment is too fast to measure sensibly. Far less than a second on my machine.

Perhaps the problem lies elsewhere?

  • May be! I'm still searching. Any hint? On my machine this code is very slow, but is fast as you say with MouseUP. – Redax May 12 '11 at 09:18