I have a function that I can implement in two different ways. Each way has its own advantages, and performance depends on the arguments it will be given. Since each implementation has several short circuits, performance can be dramatically different compared to the other one, so I thought to wrap the two implementations in one that "magically" uses the faster one.
I normally wouldn't care about this kind of optimizations, but the function gets called a lot, and the short circuits are too tasty to not give this trick a try.
However, this is way harder than I thought it would be, and I realized I don't have enough knowledge to do this properly.
What I thought to have is something along the lines of:
var v1Time = v1.getExecTimeEstimate(arg1, arg2);
var v2Time = v2.getExecTimeEstimate(arg1, arg2);
var function = v1Time < v2Time ? v1 : v2;
return function.execute(arg1, arg2);
Where getExecTimeEstimate
would return a float/double. This value shouldn't be an actual estimate of the execution time, but just something that allows me to compare it to the other value, relatively, not absolutely.
What I tried is counting the most basic operations and returning that value. For instance if the function would do 30 comparisons, 20 reads (from whatever data structure or memory) and 10 writes, I would return 60. This works, but I can already tell it is very imprecise (not acceptably-imprecise).
Another thing that (cosmetically) worries me, is that I will be inevitably forced to add some information about the performance also in arg1 and arg2's classes.
How would you implement this? Is this a good idea? Are there other approaches? Do you know of any software that makes use of this kind of tricks?
Thank you in advance for your answers, and please forgive my poor english.
Collections.sort()
in the JDK.