Utility Classes: Speed vs Not Breaking the Object-Oriented Paradigm

Advertisemen

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;    
    }
@Override
    public int intValue() {
return this.a > this.b ? this.a : this.b;
    }

@Override
    public double doubleValue() {
return (double)intValue();
    }

@Override
    public float floatValue() {
return (float)intValue();
    }

@Override
    public 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

Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

Tidak ada komentar:

Posting Komentar

© Copyright 2017 Game Engine Tutorial