Minh Ngo
Minh Ngo

Reputation: 289

How can I remove duplicated from my code in Java?

I wrote a test that will run recursion Fibonacci for 40 and run memoization recursion Fibonacci for 40 and compare the time to be at least one order of magnitude different. This is what I get so far:

      @Test
  void MemoizedMagnitudeDifferentFromRecursion(){
    Fibonacci simpleRecursiveFibonacci = new SimpleRecursiveFibonacci();
    Fibonacci memoizedRecursiveFibonacci = new MemoizedRecursiveFibonacci();
    int n = 40;

    long recursionStartTime = System.nanoTime();
    simpleRecursiveFibonacci.fibonacci(n);
    long recursionTime = System.nanoTime() - recursionStartTime;

//The code below does the same as the code above, how can I remove duplicated code?
    long memoizedStartTime = System.nanoTime();
    memoizedRecursiveFibonacci.fibonacci(n);
    long memoizedTime = System.nanoTime() - memoizedStartTime;

    assertTrue(recursionTime/memoizedTime > 1);
  }

Upvotes: 0

Views: 64

Answers (1)

Thiyagu
Thiyagu

Reputation: 17920

Extract the logic to a function and pass the logic to be run as a Runnable. Let the function run the piece of logic passed in and return the time it took to run it.

private long execute(Runnable runnable) {
    long startTime = System.nanoTime();
    runnable.run();
    return System.nanoTime() - startTime;
}

Call it as

long recursionTime = execute(() -> simpleRecursiveFibonacci.fibonacci(n));
long memoizedTime = execute(() -> memoizedRecursiveFibonacci.fibonacci(n));
assertTrue(recursionTime/memoizedTime > 1);

One more option (as suggested by SystemGlitch@) is to pass an instance of Fibonacci and an int and call fibonacci inside the method.

private long execute(Fibonacci fibonacciInstance, int n) {        
    long startTime = System.nanoTime();
    fibonacciInstance.fibonacci(n);
    return System.nanoTime() - startTime;
}

Call it as

long recursionTime = execute(simpleRecursiveFibonacci, n);
long memoizedTime = execute(memoizedRecursiveFibonacci, n);
assertTrue(recursionTime/memoizedTime > 1);

Upvotes: 2

Related Questions