IMO, it is unlikely that you will improve on the performance of this by micro-optimizing it. But you could try:
You could try using the ternary operator instead of if
... else
. The JIT compiler should treat the two forms as the same and produce equivalent native code for them. But it might not.
Patricia Shanahan's idea could work; see https://stackoverflow.com/a/49837300/139985
This method should be small enough for the JIT compiler to automatically inline the method at the native code level. But you could inline the code by hand by replacing calls to the method with the method's body.
You seem to have done some measurement, and that this is the basis of your decision that this section of the code needs to be optimized.
I would advise you to carefully look at your benchmarking methodology. Make sure that your results are not being distorted by the effects of JVM warmup or GC1.
You commented:
Only I need is to multiply two vectors. These vectors are saved in special structures. But this question was stupid from me. It works really good and the speed is not bad. Users cannot seem some difference. But I was only interesting if it is possible to improve this casting.
Standard advice on optimization is to spend your effort where it is actually needed. In this case:
- If the users think it is fast enough, that should be good enough.
- If they don't, then benchmark and profile so that:
- you can decide if this is the part of the codebase that you should be optimizing,
- you can measure the effects of your optimization ... reliably, and
- you can know when to stop.
1 - When someone quotes figures where the times measured are just a few seconds, there is always the risk that these represent once-off measurements rather than averages of multiple repetitions in a warmed up JVM.