I'm using java 11.
Let's say I have this code snippet where we're handling the completable future response:
service.processAsync(context)
.thenApply(this::doSimpleStuff)
.thenApply(this::doAnotherExtraStuff)
.thenApply(this::doFinalStuff)
.exceptionally(this::handleError);
If I fold all my doSimpleStuff, doAnotherExtraStuff and doFinalStuff into one function would it make a difference performance-wise?
Will this code run faster or will this be just less readable?
service.processAsync(context)
.thenApply(this::doEverythingInOneFunction)
.exceptionally(this::handleError);
You might get a performance gain which may be very negligible since you are removing the processing of thenApply(), But if all 3 methods needs to be run sequentially in any case, then why to even consider the first approach and instead create a new method which will call other 3 and use the new one.
service.processAsync(context, id)
.thenApply(this::callerMethod)
.exceptionally(this::handleError);
callerMethod() {
doSimpleStuff();
doAnotherExtraStuff();
doFinalStuff();
}
As @Himanshu mentioned, the performance benefit gained will be negligible, so much so that you should not depend on it as justification unless you are doing something really performance intensive (in which case, there are much higher priority things to fix before trying to stick all of the functions in one methond).
But to contrast the answer that @Himanshu gave, I would encourage you to keep the functions separate. It allows you to swap out a function for another should an implementation detail need to change in the future, and it lets you keep your code base free of ad-hoc simplification functions all over the place. Those tend to be a place where bugs hide.
But truthfully, it's not much loss either direction, so do what makes sense for your situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With