The lazy-loading property pattern in JavaScript | Code it | Scoop.it

Traditionally, developers have created properties inside of JavaScript classes for any data that might be needed within an instance. This isn’t a problem for small pieces of data that are readily available inside of the constructor. However, if some data needs to be calculated before becoming available in the instance, you may not want to pay that cost upfront.

 

It may not be efficient to perform a calculation upfront if you aren’t sure the property will be used. Fortunately, there are several ways to defer these operations until later.

 

The on-demand property pattern

The easiest way to optimize performing an expensive operation is to wait until the data is needed before doing the computation. For example, you could use an accessor property with a getter to do the computation on demand

 

The messy lazy-loading property pattern

Only performing the computation when the property is accessed is a good start. What you really need is to cache the information after that point and just use the cached version. But where do you cache that information for easy access? The easiest approach is to define a property with the same name and set its value to the computed data

 

The only-own lazy-loading property pattern for classes

If you have a use case where it’s important for the lazy-loaded property to always exist on the instance, then you can using Object.defineProperty() to create the property inside of the class constructor. It’s a little bit messier than the previous example, but it will ensure that the property only ever exists on the instance

 

The lazy-loading property pattern for object literals

If you are using an object literal instead of a class, the process is much simpler because getters defined on object literals are defined as enumerable own properties (not prototype properties) just like data properties. That means you can use the messy lazy-loading property pattern for classes without being messy

 

Conclusion

The ability to redefine object properties in JavaScript allows a unique opportunity to cache information that may be expensive to compute. By starting out with an accessor property that is redefined as a data property, you can defer computation until the first time a property is read and then cache the result for later use. This approach works both for classes and for object literals, and is a bit simpler in object literals because you don’t have to worry about your getter ending up on the prototype.

One of the best ways to improve performance is to avoid doing the same work twice, so any time you can cache a result for use later, you’ll speed up your program. Techniques like the lazy-loading property pattern allow any property to become a caching layer to improve performance.

 

read this post with more details and code examples at https://humanwhocodes.com/blog/2021/04/lazy-loading-property-pattern-javascript/