> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/thymeleaf/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/thymeleaf/i.-using-thymeleaf/6-iteration/6.3-optimizing-through-lazy-retrieval-of-data.md).

# 6.3 通过数据的懒惰检索实现优化

有时我们可能想要优化对数据的集合（比如来自于数据库）的检索。如果这些集合确实要被使用，才会被检索。

```
实际上，这可以被应用到任何一块数据。这种场景的最普遍案例是给出集合在内存中的大小，遍历检索数据。
```

为此，Thymeleaf提供了一种机制，来懒惰加载上下文变量。实现了`ILazyContextVariable`接口的上下文变量————最有可能的是扩展了它的`LazyContextVariable`默认实现，将会在执行的时候被解析。比如：

```java
context.setVariable(
     "users",
     new LazyContextVariable<List<User>>() {
         @Override
         protected List<User> loadValue() {
             return databaseRepository.findAllUsers();
         }
     });
```

即使没有关于此变量的惰性的知识，也可以使用它。在如下代码里：

```markup
<ul>
  <li th:each="u : ${users}" th:text="${u.name}">user name</li>
</ul>
```

但是同时，如果下面代码里的`condition`的值为`false`，那么上面的代码不会被初始化（它的`loadValue()`方法不会被调用）。

```markup
<ul th:if="${condition}">
  <li th:each="u : ${users}" th:text="${u.name}">user name</li>
</ul>
```
