If performance is critical, you could use a getter in combination with memoization of the results. This way, you'd delay evaluation until the first time the property was accessed, but wouldn't have to recalculate it on subsequent accesses.
constmemoize=<Textends(arg:any)=>any>(fn:T)=>{typeIn=Parameters<T>[0]typeOut=ReturnType<T>constresults=newMap<In,Out>()return(arg:In)=>{if(results.has(arg)){returnresults.get(arg)asOut}constresult=fn(arg)results.set(arg,result)returnresultasOut}}constexpensiveUpper=(name:string)=>{conststart=Date.now()while(Date.now()<start+1000){/* hang */}returnname.toUpperCase()}classPerson{constructor(publicname:string){}private_memoizedUpper=memoize(expensiveUpper)getupper(){returnthis._memoizedUpper(this.name)}}
Thanks for the reply! Yes memoization / caching of getters is cool but I often think of it as too much boiler plate, then there's the async issue 🙄. But I do appreciate your other example of using field initializers outside the constructor.
Yeah memoization is only really suitable where you need the performance boost. If you do need it though, you only need to write the boilerplate once, or zero times if you use a library. It can be adapted for asynchronous usage, as long as the memoized function always produces the same output from the same inputs. That wouldn't be the case when calling a web API, but might be the case if the asynchrony is due to carrying out expensive computation on a worker thread or something.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You can use field initializers outside the constructor to avoid repeating the field names:
If performance is critical, you could use a getter in combination with memoization of the results. This way, you'd delay evaluation until the first time the property was accessed, but wouldn't have to recalculate it on subsequent accesses.
Thanks for the reply! Yes memoization / caching of getters is cool but I often think of it as too much boiler plate, then there's the async issue 🙄. But I do appreciate your other example of using field initializers outside the constructor.
Yeah memoization is only really suitable where you need the performance boost. If you do need it though, you only need to write the boilerplate once, or zero times if you use a library. It can be adapted for asynchronous usage, as long as the memoized function always produces the same output from the same inputs. That wouldn't be the case when calling a web API, but might be the case if the asynchrony is due to carrying out expensive computation on a worker thread or something.