0

I have a question about handling click event of button. I have already read this article

I know the difference by code, styling, readable... But I do not know the difference about performance in these two ways:

  • The first way:

    buttonA.setOnClickListener(this).

  • The second way:

    buttonB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To do something } });

Has anyone found out this?

Huy Nguyen
  • 1,032
  • 14
  • 38
  • Sorry, your article is only compare two methods that is not the answer I need to know. I edited my question – Huy Nguyen Mar 06 '17 at 10:19
  • Possible duplicate of [Difference between OnClick() event and OnClickListener?](http://stackoverflow.com/questions/7453299/difference-between-onclick-event-and-onclicklistener) – Shrenik Shah Mar 06 '17 at 10:51

3 Answers3

3

If there is one you shouldn't worry about it because it's that small. Readability is much more important.

'The second' way creates one more object.

user2479595
  • 339
  • 2
  • 11
0

In second way you are creating new View.OnClickListener, Objects take time to create, and memory to keep them available.

I'm avoiding implementing listener in my classes, i prefer to use annonymous class (Second way), if I have to use listener in many places than I am creating field that holds it.

Drake29a
  • 896
  • 8
  • 23
0

The first method implements the OnCLickListener class whereas the second method creates an Anonymous class.
The first method will result in your code being more organised and neat, but if you have multiple buttons, then you have to add more code to the OnCLick method.
Whereas in Anonymous classes, every time a click event occurs, a new object is created, which really doesn't affect the performance. The effect is negligible. But since the objects are dynamically created, which means the Garbage Collector should free the associated memory once the object is no longer being used.

TO summarise, there is almost negligible difference in both their performances. Deciding which one to use mostly depends on your need/requirement.