Throughout pretty much all the time I've been coding in Java or C# or probably even C++ I've used utility classes.
Utility classes can be informally defined as classes containing static functions to perform generic tasks that would otherwise be repeated throughout your code. Essentially just storing commonly used functions.
Mainly I use them for reading and writing a list of strings to/from a file (though I think Java 1.8 has *finally* implemented a function to do that in the standard library).
Another simple example of a utility function would be to take two integers, a and b, and return which of these is the maximum.
Max(a, b): return a > b ? a : b;
This function can be defined in a utility class as:
public class MaxUtility {
public static int max(int a, int b) {
return a > b ? a : b; }
}
However, this breaks the principles of OOP (for more info read this)
The alternative way, utilising OOP is this mess:
public class Max extends Number {
private final int a;private final int b;public Max(int x, int y) {
this.a = x;this.b = y;}
@Overridepublic int intValue() {
return this.a > this.b ? this.a : this.b;}
@Overridepublic double doubleValue() {
return (double)intValue();}
@Overridepublic float floatValue() {
return (float)intValue();}
@Overridepublic long longValue() {
return (long)intValue();}
}
Lots more code to achieve the same thing...
In the comments of the page I linked above, it is talked about the OOP method making the GC work more often as you are constantly creating instances of the Max class whenever you need to use the max function.
So I tested that out.
The results are quite shocking.
On 100,000 max functions, the utility method takes 5ms +/- 1ms
Whereas the OOP method takes 12.7ms \pm 3.1ms
A massive performance reduction just to follow OOP standards.
This just reiterates that I'm going to keep doing things the same way
Tidak ada komentar:
Posting Komentar