Method inlining example. (#6520)

* Method inlining example.

* Test added
This commit is contained in:
cdjole 2019-03-13 16:31:14 +01:00 committed by maibin
parent cd57889230
commit 47e617fc39
3 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,19 @@
package com.baeldung.inlining;
public class ConsecutiveNumbersSum {
private long totalSum;
private int totalNumbers;
public ConsecutiveNumbersSum(int totalNumbers) {
this.totalNumbers = totalNumbers;
}
public long getTotalSum() {
totalSum = 0;
for (int i = 1; i <= totalNumbers; i++) {
totalSum += i;
}
return totalSum;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.inlining;
public class InliningExample {
public static final int NUMBERS_OF_ITERATIONS = 15000;
public static void main(String[] args) {
for (int i = 1; i < NUMBERS_OF_ITERATIONS; i++) {
calculateSum(i);
}
}
private static long calculateSum(int n) {
return new ConsecutiveNumbersSum(n).getTotalSum();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.inlining;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ConsecutiveNumbersSumUnitTest {
private static final int TOTAL_NUMBERS = 10;
@Test
public void givenTotalIntegersNumber_whenSumCalculated_thenEquals() {
ConsecutiveNumbersSum consecutiveNumbersSum = new ConsecutiveNumbersSum(TOTAL_NUMBERS);
long expectedSum = calculateExpectedSum(TOTAL_NUMBERS);
assertEquals(expectedSum, consecutiveNumbersSum.getTotalSum());
}
private long calculateExpectedSum(int totalNumbers) {
return totalNumbers * (totalNumbers + 1) / 2;
}
}