This week's book giveaway is in the Other Open Source APIs forum. We're giving away four copies of Storm Applied and have Sean Allen, Peter Pathirana & Matthew Jankowski on-line! See this thread for details.
That is a big difference and to much in most cases.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Joined: Jan 12, 2010
Thanks for the feedback. You got that error is because the field is not public - comparators can only access public fields.
You were spot on about the speed, though! Wow, it's abysmal - 20 to 70x slower than a normal comparator. I added a 'testCapacity' routine to the JUnit tests, and discovered what you meant.
I tried some different methods, and came up with this one. It is flexible, in that it will let you sort on multiple columns with different sort criteria, like DynamicComparer... but it performs much faster, and scales well. It also allows you to access private fields.
It's still slower than a custom comparator, so if you have a need for a one off fast sort, hand coding is probably the best way to go. This routine is mainly useful for small arrays, such as you might use during web development, when you're presenting a limited result set to the user, letting them choose their sort columns, and don't want to have to hit the database every time they click the sort button.
Give this one a whirl, I think you'll like it better. My timings are below:
Standard method: Sorted 100000 items in 47 milliseconds. This is the usual Java method, where you create a new custom comparator for each sort you want.
New method: Sorted 100000 items in 172 milliseconds. This is the new method I created, which uses a single custom comparator that handles all possible sorts you might want, with per-field direction and case sensitivity.
Lazy method: Sorted 100000 items in 3437 milliseconds. This method is like 'new', but calls a pre-done compareTo proc to get you out of handing-coding the compareTo proc. The pre-done compareTo proc uses reflection to look up the fields, so while it saves you coding work, this is the slowest method.