nudge icon indicating copy to clipboard operation
nudge copied to clipboard

memoize as many function calls as possible

Open erikng opened this issue 3 years ago • 1 comments

Right now we flip a boolean var when actions have been triggered so they don't spam the console, but the functions are still continuously being called.

A lot of these could be memoized to fix this.

https://www.hackingwithswift.com/plus/high-performance-apps/using-memoization-to-speed-up-slow-functions

https://medium.com/@mvxlr/swift-memoize-walk-through-c5224a558194

erikng avatar Aug 25 '21 19:08 erikng

If the function is only ever instantiated once, we can use a much simpler pattern for memoization: Note: This is psuedo-swift

func getInfo() -> () -> String {
	var infoString = nil
    
	func getInfoForReal() -> String {
                if infoString == nil {
                    infoString = doThingToGetInfo()
                }
		return infoString
	}
    
	return getInfoForReal
}

The first time the function is called, infoString is nil and when it calls getInfoForReal(), it then kicks off the process that actually gets the value and sets infoString.

The next time this is called, infoString is already defined and getInfoForReal just passes back the value rather than trying to set it again. So long as the same instance of 'getInfo()` is called each time, this state will remain in memory (as long as nudge is open?)

In the page below, they outline how to do it inside of a class, which makes a lot of sense (the class instantiates the function, so you don't have to worry about passing a copy around). Not sure if that is needed here, but you can check out that pattern here if interested: https://weekly.elfitz.com/2020/05/21/use-functions-scope-to-memoize-your-results/

I'll try messing with this at some point :D Wanted to get the reading done first.

natewalck avatar Aug 26 '21 15:08 natewalck