When should one avoid using NHibernate's lazy-loading feature?

前端 未结 5 408
礼貌的吻别
礼貌的吻别 2021-01-02 15:32

Most of what I hear about NHibernate\'s lazy-loading, is that it\'s better to use it, than not to use it. It seems like it just makes sense to minimize database access, in

5条回答
  •  生来不讨喜
    2021-01-02 16:25

    There are clear performance tradeoffs between eager and lazy loading objects from a database.

    If you use eager loading, you suck a ton of data in a single query, which you can then cache. This is most common on application startup. You are trading memory consumption for database round trips.

    If you use lazy loading, you suck a minimal amount of data in a single query, but any time you need more information related to that initial data it requires more queries to the database and database performance hits are very often the major performance bottleneck in most applications.

    So, in general, you always want to retrieve exactly the data you will need for the entire "unit of work", no more, no less. In some cases, you may not know exactly what you need (because the user is working through a wizard or something similar) and in that case it probably makes sense to lazy load as you go.

    If you are using an ORM and focused on adding features quickly and will come back and optimize performance later (which is extremely common and a good way to do things), having lazy loading being the default is the correct way to go. If you later find (through performance profiling/analysis) that you have one query to get an object and then N queries to get the N objects related to that original object, you can change that piece of code to use eager loading to only hit the database once instead of N+1 times (the N+1 problem is a well known downside of using lazy loading).

提交回复
热议问题