Event Handler performance

前端 未结 4 523
礼貌的吻别
礼貌的吻别 2021-02-04 08:59

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.Cl         


        
4条回答
  •  鱼传尺愫
    2021-02-04 09:35

    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.

提交回复
热议问题