DEV Community

muriuki muriungi erick
muriuki muriungi erick

Posted on

Code optimization

This is part of everyday thoughts in python,data engineering and machine learning

It's important to consider the complexity of a function call. Basically, if we have a complex call in our program, the program becomes slower. Sometimes complexity might find its way into our workspace when dealing with function calls. It's, therefore, a good practice to look keenly for any recursive or nested functions since they are the main cause of slowing our code. To understand this, let's have a sample of the Fibonacci function

def fib (n):
    if n <=1 :
        return n
    else:
        return  fib(n-1) + fib(n-2)
result= fib(10)
print(result)
Enter fullscreen mode Exit fullscreen mode

Time complexity of the above code is O(2^n)

Here the 10th number in the Fibonacci sequence is calculated by recursively calling the Fibonacci function with a smaller function argument until it reaches the base case of n=0 and n=1. In such cases, the algorithm's time complexity grows exponentially first in cases of huge values of n. in practice; we would like to use a friendly algorithm to minimize calculation repetitions. A friendly algorithm for such a scenario can be as given below.

def fib_optimized(n):
    if n < 2:
        return n
    else:
        fib_prev, fib_curr = 0, 1
        for i in range(2, n+1):
            fib_next = fib_prev + fib_curr
            fib_prev = fib_curr
            fib_curr = fib_next
        return fib_curr
result = fib_optimized(10)
print(result)

Enter fullscreen mode Exit fullscreen mode

The time complexity for the above function is O(n) hence more optimized.
From this, we can take home some points in comparison between an algorithm's time complexity and a function call's time complexity.

  1. The time complexity of an algorithm depends on the size of the input data, and it is basically the amount of time taken for an algorithm to solve a certain problem

  2. The time complexity of a function depends on the function itself.
    Therefore it is vital to select the right algorithm for the problem at hand and optimize the algorithm as much as possible to minimize the unnecessary complexity.

happy learning!!

Top comments (0)