What is Lazy Loading?

前端 未结 13 1370
栀梦
栀梦 2020-11-29 16:46

What is Lazy Loading?

[Edit after reading a few answers] Why do people use this term so often?

Say you just use a ASP/ADO recordset and load it with data or

13条回答
  •  天命终不由人
    2020-11-29 17:04

    Here's an example from some actual Python code I wrote:

    class Item(Model):
        ...
        @property
        def total(self):
            if not hasattr(self, "_total"):
                self._total = self.quantity \
                      + sum(bi.quantity for bi in self.borroweditem_set.all())
            return self._total
    

    Basically, I have an Item class which represents an item in our inventory. The total number of items we have is the number that we own plus the sum of all of the items that we're borrowing from various sources. These numbers are all stored in our database, and it would be pointless to calculate this until the total is actually requested (since often Items will be used without the total being requested).

    So the total property checks whether the _total field exists. If it doesn't, then the property code queries the database and computes it, then stores the value in the _total field so that it need not be recomputed the next time it's requested.

提交回复
热议问题