Here we see how overloading can improve performance. We implement a feature with 2 separate designs: overloaded methods, and a nested if-statement.
public class Program {
static int add(int value1, int value2) {
return value1 + value2;
}
static int add(int value1, int value2, String value3) {
return value1 + value2 + value3.length();
}
static int addNoOverload(int value, int value2, String value3) {
if (value3 == null) {
return value + value2;
} else {
return value + value2 + value3.length();
}
}
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
// Version 1: use overloaded methods.
for (int i = 0; i < 1000000000; i++) {
int result = add(10, i) + add(5, i,
"carrot");
if (result == 0) {
return;
}
}
long t2 = System.currentTimeMillis();
// Version 2: use method with if-statement.
for (int i = 0; i < 1000000000; i++) {
int result = addNoOverload(10, i, null)
+ addNoOverload(5, i,
"carrot");
if (result == 0) {
return;
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
289 ms, add
329 ms, addNoOverload