Remember frequent input for faster execution of a function in javascript
Rajnish Katharotiya
Posted on April 23, 2020
Photo by JESHOOTS.COM on Unsplash
In every project, we encounter anyone function which will be using frequently into the app or which have the possibility of the same input again-n-again. So, shouldn't we do something to prevent execution if give input already passed before? What you'll do it? ( please comment me down below, will love to get more solutions 😊 ).
Before moving forward, let me welcome you in a new episode of series called Javascript Useful Snippets, In this series, I'm sharing shortcodes and useful javascript functions which can help you to make your code more efficient and neat. So, if you haven't read previous articles please check it out here otherwise stay tuned till the end to learn something new 🤩.
Let's start with a very simple example, assume we have a function to get square of a given number. And we are passing random numbers from 1-10. and number 3 is passed through function five times for execution where on first execution the only system had found out that for input 3 output will be 9 still it'll execution square function and user have to wait unnecessarily four times of execution.
In this situation, we can use a function called memoize(), this function will remember input and respective output once it's passed through execution. so, we can save time. Now, let me show you what it does:-
const memoize = fn => {
const cache = new Map();
const cached = (val) => {
return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
};
cached.cache = cache;
return cached;
};
So, here in function, i've created first empty object(cache) through map ( new Map() is a constructor to create object to store key-value pair data, you can read it more on here ) and in next i've created another function called cached, which is using cache object to first validate if given input is stored into it and or not, if yes, return it direct from thier otherwise will execute function and set into cache with output of it. In last, it's just returning cached object with result value.
Let's look it with an example:
const stringOne = "Hello World";
const stringTwo = "😎";
const byteSize = str => new Blob([str]).size;
const memoziedByteSize = memoize(byteSize)
var t0 = performance.now();
memoziedByteSize(stringOne)
memoziedByteSize(stringTwo)
var t1 = performance.now();
console.log("First time took " + (t1 - t0) + " milliseconds.");
var t2 = performance.now();
memoziedByteSize(stringOne)
memoziedByteSize(stringTwo)
var t3 = performance.now();
console.log("Second time took " + (t3 - t2) + " milliseconds.");
In the above example, I've used function to get a byte size of a given string. So first created two string constants and declared byteSize function. Next stored memorized function in new constant(memoziedByteSize) after wrapping operational function with memorize function.
Next is the execution part, for monitor processing time I've used a function called performance.now() ( it'll return current time, you can read about from here ) before and after the execution and console difference between them. And that same process I've done twice with the same input stings. Let's see what console look like:-
First time took 1.0550000006332994 milliseconds.
Second time took 0.005000001692678779 milliseconds.
Wow, clearly we can see difference right? So, this one was just a simple execution to get byteSize. but think if it could have complex process then how much time it can save. ( for me I had very complex execution and it'd work ). This snippet work for me like a charm so, I thought to share it with you too. I hope you liked it ( if yes, hit like ❤️ button ) and I hope you learned something new. if yes? hit follow to learn every day something new.😅
check video tutorial on:
Posted on April 23, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
April 15, 2022