More of a technical question than a philosophical, because I am mainly interested in the intelligence of the LWC cache and any performance implications.

I use the lazy-init pattern extensively in Apex, when implementing complex objects. The code usually looks something like this

public List<String> Errors {
    public get {
        if (Errors == null) Errors = getErrors();
        return Errors;
    private set; 

Where Errors is an object property and getErrors() is a private function that initializes the List of errors (where I know, that once initialized, the errors will never change during the life-time of the object).

Now considering client/server round trips: What happens in LWC under the hood, if I use @wire to import and call an apex method that retrieves a list of objects with lazy-init properties? My JavaScript / HTML may access said properties. Are there any unnecessary round trips where it would be faster / more efficient to simply load all Properties with the constructor?

PS: I recently started with LWC, so I'm always thankful if you point me to existing resources that already answer my question.

  • Adding properties in class and returning as datatype is fine. I have misread your question. Deleted my answer. – salesforce-sas Aug 16 '19 at 14:21

When LWC actually calls some Apex, the AuraEnabled results are serialized to JSON, allowing it to be transported over HTTP (AJAX) to the client. That means the whole object (at least the AuraEnabled parts) is walked, during the serialization, to access all property values at that time. This means your properties will all get read (and therefore all your lazy loading private methods called as a side effect) at that point.

LWC communications do not get partial objects back and then fetch other parts later. (This is different to your application allowing partial object trees to be returned, but that's code you write to set up and return the required Apex objects.)

  • Thanks Phil, I realised I have misread the question – salesforce-sas Aug 16 '19 at 14:19
  • 2
    No worries. Your contributions are usually pretty good so it's OK to have a Friday moment ;) – Phil W Aug 16 '19 at 14:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.