Android – How To Implement Automatic Functions Memoization Technique In Kotlin?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Implement Automatic Functions Memoization Technique in Kotlin ?).

In this article, we will learn about how to implement Automatic Functions Memoization Technique in Kotlin. Memoization is a technique used to optimize the program-execution speed by caching the results of expensive function calls and reusing their ready values when they are required again. Although memoization causes an obvious trade-off between memory usage and computation time, often it’s crucial to provide the desired performance. This article explains about Automatic Functions Memoization Technique work flows in Kotlin.

To understand the Automatic Functions Memoization Technique in Kotlin, we cover the below topics as below :

  • Overview
  • How to Implement Technique?
  • How Technique Works?

A famous quote about learning is :

“That is what learning is. You suddenly understand something you’ve understood all your life, but in a new way.”

So Let’s begin.

Overview

We can understand about Memoization as:

  • A technique used to optimize the program-execution speed by caching the results of expensive function calls and reusing their ready values when they are required again.
  • An obvious trade-off between memory usage and computation time, often it’s crucial to provide the desired performance. Usually, we apply this pattern to computationally-expensive functions.
  • It can help to optimize recursive functions that call themselves multiple times with the same parameters values.

Memoization can easily be added internally to function implementation. However, in this article, we are going to create a general-purpose, reusable memoization mechanism that could be applied to any function.

How to Implement Technique?

In this section, We will understand how to implement it and What steps are required for implementation.

Step 1 – Declare a Memoizer class responsible for caching the results:

class Memoizer<P, R> private constructor() { 
   private val map = ConcurrentHashMap<P, R>() 
   private fun doMemoize(function: (P) -> R):
         (P) -> R = { param: P ->
            map.computeIfAbsent(param) { param: P ->
                function(param)
                    }
             }
   companion object { 
       fun <T, U> memoize(function: (T) -> U):
       (T) -> U =
                 Memoizer<T, U>().doMemoize(function)
     }
 } 

Step 2 – Provide a memoized() extension function for the (P) -> R function type:

fun <P, R> ((P) -> R).memoized(): (P) -> R = Memoizer.memoize<P, R>(this)

How Technique Works?

The memoize() function takes an instance of a one-argument function as its argument. The Memoizer class contains the ConcurrentHashmap<P, R> instance, which is used to cache the function’s return values. The map stores functions passed to memoize() as arguments as the keys, and it puts their return values as its values.

First, the memoize() function looks up the value for a specific parameter of the function passed as an argument. If the value is present in the map, it is returned. Otherwise, the function is executed and its result is returned by memoize() and put into the map. This is achieved using the handy inline fun <K, V> ConcurrentMap<K, V>.computeIfAbsent(key: K, defaultValue: () -> V): V extension function provided by the standard library.

Additionally, we can provide an extension function, memoized(), for the Function1 type, which will allow us to apply the memoize() function directly to the function references.

Note that the under the hood functions in Kotlin are compiled to the FunctionN interface instances in the Java bytecode, where N corresponds to the number of function arguments. We can declare an extension function for a function. For example, in order to add an extension function for a function taking two arguments, (P, Q) -> R, we need to define an extension as fun <P, Q, R> Function2<P, Q, R>.myExtension(): MyReturnType.

Now, take a look at how we can benefit from the memoized() function in action. Consider a function that computes the factorial of an integer recursively:

fun factorial(n: Int): Long = if (n == 1) n.toLong() else n * factorial(n - 1)

We can apply the memoized() extension function to enable caching of the results:

val cachedFactorial = ::factorial.memoized()
println(" Execution time: " + measureNanoTime { cachedFactorial(12) } + " ns")
println(" Execution time: " + measureNanoTime { cachedFactorial(13) } + " ns")

The above code snippet gives the following output on a standard computer:

Execution time: 1547274 ns
Execution time: 24690 ns

As we can see, even though the second computation requires a higher number of recursive calls of the factorial() function, it takes much less time than the first computation.

We can implement similar automatic memoization implementations for other functions that take more than one argument. In order to declare an extension function for a function taking N arguments, we’d have to implement an extension function for the FunctionN type.

That’s all about in this article.

Related Other Articles / Posts

Conclusion

In this article, we understood about how to implement Automatic Functions Memoization Technique in Kotlin. This article explained about Automatic Functions Memoization Technique work flows in Kotlin.

Thanks for reading! I hope you enjoyed and learned about Automatic Functions Memoization Technique concepts in Kotlin. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find other articles of CoolMonkTechie as below link :

You can also follow official website and tutorials of Android as below links :

If you have any comments, questions, or think I missed something, leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Loading

Summary
Android - How To Implement Automatic Functions Memoization Technique In Kotlin?
Article Name
Android - How To Implement Automatic Functions Memoization Technique In Kotlin?
Description
This article explains about Automatic Functions Memoization Technique work flows in Kotlin. This technique usually applies in computationally-expensive functions.
Author

4 thoughts on “Android – How To Implement Automatic Functions Memoization Technique In Kotlin?”

  1. its awesome that this blog providing pure gold standard technical content for free I really appreciate the interest and time the Authors are putting into this

    Reply
  2. I love your blog.. very nice colors & theme. Did you create this website yourself? Plz reply back as I’m looking to create my own blog and would like to know wheere u got this from. thanks

    Reply
    • Thank you so much, I really appreciate hearing that from you. For your blog, you can use free WordPress themes.

      Reply

Leave a Comment