Giter VIP home page Giter VIP logo

mnemonik's Introduction

MnemoniK

Hex.pm

Simple memoization extension function for Kotlin

Rationale

Suppose you have a performance-intensive function that you must call repeatedly. A common solution is to build an internal cache (...) Memoization is a feature built into a programming language that enables automatic caching of recurring function-return values.

Functional Thinking - Neal Ford

Kotlin doesn't have yet any similar feature in it's tools. Although it might have it at some point I wanted to experiment a bit with this technique so that's why I created the lib.

Important

Functions must be pure for the caching technique to work.

A pure function is one that has no side effects: it references no other mutable class fields, doesn't set any values other than the return value, and relies only on the parameters for input.

In other words, you can reuse cached results successfully only if the function reliably returns the same values for a given set of parameters.

Also, when passing or returning Objects, make sure to implement both equals and hashcode for the cache to work properly.

Usage

Having a function like:

fun anExpensiveFun(someArg: Int, someOtherArg: Boolean): String = { /*...*/ }

You can create a memoized version of it by just calling an extension function over its reference like this:

val memoized = ::anExpensiveFun.memoize()

Now memoized is the same function as anExpensiveFun but is wrapped in a lambda that contains an internal cache, meaning that the first call to:

memoized(5, true)

Will just execute the function and return the value. But a second call with the same arguments will retrieve the previous value from cache.

Note that we're storing values in a memory cache, so try to have that in consideration when doing a relatively big amount of calls to your memoized function or if you use big objects as parameters or return type.

If you want to specify how big the cache has to be you can do it like the following:

val memoized = ::anExpensiveFun.memoize(50)

By default the cache size is initialized with 256.

By default HashMap and ConcurrentHashMap are used as caches but you can also pass any MutableMap and ConcurrentMap instances which allows custom control of the cache.

val map = ConcurrentHashMap<Int, Boolean>(50)
val memoized = ::anExpensiveFun.memoize(cache = map)

// clear the cache at the end
map.clear

Note: The same approach also works for suspend functions.

Limitations

Currently this library only supports up to 5 function parameters.

Note that the memoization might not be thread safe for the first call, subsequent calls are safe as they will simply retrieve from cache.

Distribution

Add as a dependency to your build.gradle with Jitpack

License

MIT License

Copyright (c) 2022 aballano

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

mnemonik's People

Contributors

aballano avatar mpe85 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

mnemonik's Issues

Publish on maven cental or jcenter

First of all, thanks for this great little library.
Would be nice if you could publish it on the maven central or jcenter repository, since we usually only use libraries available on these repositories.

Thread-safe memoize

Hey @aballano , thanks for great extension.
It works well in one-thread environment.
What do you think about overloading extension functions to have an ablitiy to use them in mutli threading environment, e.g.:

fun <A, R> ((A) -> R).memoize(cache: MutableMap<A, R> = HashMap(DEFAULT_CAPACITY)): (A) -> R

With that approach we can put ConcurrentHashMap or others.
Usage:

private val memoizedSafeFib = ::fib.memoize(ConcurrentHashMap())
fun callMeFromDifferentThreads(arg: Int): Long = memoizedSafeFib(arg)

Could not find org.jetbrains.kotlinx:kotlinx.benchmark.runtime-jvm:0.2.0-dev-20.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.