Skip to content

Caching Memoization

Francisco Ruiz edited this page Aug 27, 2024 · 1 revision

Caching/Memoization

The dependency injection container is able to cache the methods or functions of each service, which significantly improves the performance of applications that call functions that are expensive to compute. It is also useful for large applications that make multiple calls to methods or functions that perform the same operation over and over again.

The caching system is implemented on a middleware with the lowest priority, allowing the middleware to execute as close to the service execution as possible.

js-cache-middleware.png

See Pure Functions Considerations for more information about using the caching system with non-pure functions.

Caching all methods

To enable the caching for all methods, you can use the cache option when registering the service:

container.add('Service', () => {
  return new Service();
}, { cache: true });

Caching only for specific methods

With the methods option you can specify a list of methods that should be handled by the cache if the cache is enabled.

container.add('Service', () => {
  return new Service();
}, {
  cache: true,
  methods: ['someMethod1', 'someMethod2'],
});

This caches only the methods someMethod1 and someMethod2 of the service.

Caching all methods except specific ones

With the excludeMode option you can specify a list of methods that should not be cached. This is useful if you have a large number of methods and only want to exclude some of them.

container.add('Service', () => {
  return new Service();
}, {
  cache: true,
  methods: ['someMethod1', 'someMethod2'],
  excludeMode: true,
});

This caches all the methods of the service except the methods someMethod1 and someMethod2.

No caching

The default behavior, without the cache option, is to not cache any method of the service.

container.add('Service', () => {
  return new Service();
});

1. Getting Started

2. Core Concepts

3. Middleware

4. Caching and Memoization

5. Typescript

6. Considerations

7. API Reference

8. Examples and Use Cases

9. Contributing

We welcome contributions from the community! Whether it's reporting a bug, suggesting a feature, or contributing code, your involvement is key to making Packet.js better. Please check out this section for more details.

10. Support

If you encounter any issues or bugs while using packetjs, or if you have any feature requests, please feel free to open an issue in our GitHub repository. You can report issues, track progress, and engage in discussions with the community via the following link:

11. FAQ

If you have any questions or need further assistance, feel free to reach out via the discussion board.

12. License

Clone this wiki locally