Let’s assume following code snippet:
public class NotThatWellWrittenClass {
public static void doSmth() {
/*
This code part is actually irrelevant.
*/
}
}
Some other class would use that util as following: NotThatWellWrittenClass.do(), so the only overhead is actually related to performing a method call.
I really do not like programming that way, so I would like to refactor this part of code, while not breaking clients who are using static method call. Refactored snippet:
public class NotThatWellWrittenClass {
public static void doSmth() {
new WorkUtil().doSmth();
}
}
public class WorkUtil() {
public void doSmth() {
/*
This code part is actually irrelevant.
*/
}
}
Now, code is much more Object Oriented and easier to test and reuse. It now does, however, create an extra object (memory assignement) and perform instance method call instead of static call (which are optimized by JVM differently, I guess).
So, back to the question, does following refactoring provides any noticeable overhead? Maybe it should be performed in some other manner? (I could always cache an instance to my object, but is it worth it?)
I would like to get some in-depth explanation, thanks.
Methods which are small e.g. 35 bytes long, can be inlined.
Only methods which are called often are optimised this way. e.g. 10,000 times or more.
If its rarely called, it should matter if it takes a few more nano-seconds anyway.
If WorkUtil.do() is simple enough the object allocation could be optimised away. The only alternative is to recycle the object yourself. It is fairly rare that you really need to do this.