Comparator vs Apache BeanComparator

aces. picture aces. · Jul 11, 2012 · Viewed 10.8k times · Source

Consider a simple class:

class Employee {

String name;
int sal;

....//getters and setters
}

I can create a Comparator to sort on field name for example.

class EmpSortByName implements Comparator<Employee>{

 @Override
 public int compare(Employee e1, Employee e2){
  return e1.getName().compareTo(e2.getName());
 }
}

However, looking at apache commons BeanComparator, sorting can be achieved in following way:

BeanComparator bc = new BeanComparator("name");
Collections.sort(employeeList, bc);

Thus, by using BeanComparator, I can achieve sorting with minimal code. What are the trade offs between using Comparators and BeanComparators: in terms of performance, usage scenarios (multiple fields sort, other factors)?

I also understand that to use BeanComparator, the beanutils jar has to be imported.

Answer

JB Nizet picture JB Nizet · Jul 11, 2012

The BeanComparator uses reflection to access the name property and compare the two objects. Although reflection performance has improved, it's still not as fast as accessing a field directly. Whether this is important or not depends on how many times it's called in your application, and in which context.

Another problem is that, if you refactor the method and rename it to getLastName(), the code using BeanComparator will not be refactored, and the problem will go unnoticed until runtime (or unit testing time).

Frankly, implementing a comparator is so easy that I don't think using reflection is a good idea. The benefit of avoiding 4 lines of trivial code isn't sufficient to compensate for the performance and maintainability problems it causes.