Creating stateless objects in Java
Is there any way in Java to avoid instantiating a stateless object? There is no real difference between a static function and a stateless object:
class CompareInts {
Integer compare(Integer a, Integer b) {
return a.compareTo(b);
}
static Integer compare(Integer a, Integer b) {
return a.compareTo(b);
}
The functionality of these two alternatives does the same, and in general, each stateless class can be converted to a static function. There are two main differences:
- Instantiating a static class takes both time and memory where they are not needed. You really need to keep the code you don't need to allocate an object on the heap and a pointer to the vtable.
- static functions are very limited in Java. They cannot be used with Generics, static comparisons can never be used by the class that needs to be compared.
Therefore, a static function is better in theory because it provides all the stateless functionality of a class, but without the runtime and memory overhead. A static function is much less efficient in Java because it cannot be called through a generic type. Is there a way to benefit from both worlds?
Edit
I want to write a generic class like this:
class Array<Type, Comparator> {
Type[] elements;
// array stuff
Type getMax() {
Type maxElement = Type.getSmallestLegalValue();
for (Type element : elements) {
maxElement = Comparator.compare(maxElement, element) > 0 ? maxElement : element;
}
return maxElement;
}
}
I cannot write this. I have to accept the Comparator
in constructor Array
and create an interface Comparator
that implements CompareInts
.
source to share
Use objects without saving.
If the object is stateless, you would never need to allocate more than one, in theory (like allocate one static instance and reuse it). It is unlikely that you have ever used a significant amount of memory for such objects.
Your concerns about memory usage and creation time are not concerned. In your example, you are talking about a few bytes and a few microseconds added to the whole sort operation. This is completely insignificant.
Passing the pointer this
to the method would also be negligible, and I think the optimizer will take care of that anyway.
So, put your thoughts aside and stick to clear, convenient and easy-to-use code. If you have performance issues, profile and I guarantee you won't find your bottleneck here.
source to share
Perhaps references to static methods are what you are looking for: http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
eg:.
return elements.stream().max(SomeComparator::someStaticCompareMethod);
source to share