I'm concerned about improving source code readability, and it involves reducing the size of huge methods by breaking them down into smaller (concise) methods. So, in a nutshell, let's say I have a very monolithic method that does a lot of different things, for example:
public void verHugeMethod(List<Person> people) {
for (Person person : people) {
totalAge += person.getAge();
totalHeight += person.getHeight();
totalWeight += person.getWeight();
// More calculations over class variables...
}
}
And I want to change the method to something like:
public void calculateTotalAge(List<Person> people) {
for (Person person : people) {
totalAge += person.getAge();
}
}
public void calculateTotalHeight(List<Person> people) {
for (Person person : people) {
totalHeight += person.getHeight();
}
}
public void calculateTotalWeight(List<Person> people) {
for (Person person : people) {
totalWeight += person.getWeight();
}
}
// More calculations over class variables...
My concern is about performance (time and memory) when applying this kind of refactoring. For a small list of people, it's of course not a problem, but I'm worried about the asymptotic growth of this list.
For example, for a more old-fashioned for
I can see the following impact:
// OPTION 1
public void method1() { // O(1) + O(3n)
int i = 0; // O(1)
while (int i < people.size()) { // O(n)
doSomething(people.get(i)); // O(1)
doAnotherThing(people.get(i)); // O(1)
i++; // O(1)
}
}
// OPTION 2
public void method1() { // O(2) + O(4n)
method1(); // O(1) + O(2n)
method2(); // O(1) + O(2n)
}
public void method2() { // O(1) + O(2n)
int i = 0; // O(1)
while (int i < people.size()) { // O(n)
doSomething(people.get(i)); // O(1)
i++; // O(1)
}
}
public void method3() { // O(1) + O(2n)
int i = 0; // O(1)
while (int i < people.size()) { // O(n)
doAnotherThing(people.get(i)); // O(1)
i++; // O(1)
}
}
I know how Java converts foreach directives to iterables
.
Therefore, my questions are:
- Does Java have some optimization in terms of execution or compiling?
- Should I be concerned with this kind of performance question?
Note: I know that in terms of asymptotic growth and Big-O notation we should ignore constants, but I'm just wondering about how this kind of scenario applies to Java.