First of all, is it necessary to optimize the program? Have you appreciated where you need to do this? Is it in this function?
For primitive types, the second comparison is as fast as it gets. A higher comparison cost is to load an element in the appropriate register and this is necessary for the first comparison. Once this comparison is performed, the value is already in the register, and the second operation accepts an instruction with one processor plus the possible cost of incorrect branch prediction.
Assuming integral types, the cost of the processor time of the algorithm is most likely determined in many ways by the cost of recursive calls if the compiler cannot perform tail recursion optimization. If you really need to optimize this, try compiling with all the optimization flags and analyze the assembler to determine if tail recursion optimization is being applied. If not, manually convert the algorithm from recursive to iterative.
This will have two effects: overshadow the code (avoid modifying a clean solution if you really need it), and avoid function calls.
If you are talking about C ++, and the type is complex, and the overloaded comparison operators are expensive, then the fastest performance growth is the compare method, which will return a negative number less than 0 for an equal and positive number, if more than. Then pre-compare the result before the comparison, and then perform integer checks. This will reduce the total cost of the algorithm to a single processing of real objects using expensive comparisons and return you to the original assumption.
David Rodrรญguez - dribeas
source share