SQLite 中内存数据库的优点

Advantages of an in-memory Database in SQLite

我今天从一本关于SQLite的书上读到关键字“:memory:”,但它只说了它是什么,如何使用,而且解释太简短了。所以我在这里搜索了更多信息,但无法获得 SQLite 特定信息。

  1. ':memory:'模式有什么优势? (我什么时候需要这个?)

  2. 内存数据库的性能更快?

  3. 我还需要在内存数据库上使用事务吗?

A SQLite in-memory database 的主要优势是性能:它不会读取和写入磁盘,而是将整个数据库保存在内存中。内存比磁盘快得多。您将看到旋转磁盘或重 IO 负载服务器的最大性能改进,而 SSD 则更少。

但是,这并不是解决写得不好的查询和 tables 的灵丹妙药。在您使用内存数据库来提高性能之前,请务必优化您的 table 设计、查询和索引。

主要缺点是一旦进程关闭数据库就消失了。并且数据库不能大于可用内存。

由于不需要写入磁盘,提交可能会更快,因此自动提交模式可能会更快,但出于数据完整性目的仍应使用事务。

请注意,不会变得太大的临时 SQLite 数据库可能会存储在内存中。

由于它的缺点,并且因为你的内存比存储少得多,所以在提交到内存数据库之前尝试使用临时数据库。这是通过使用 '' 作为数据库文件名来完成的。这将写入一个临时文件,但将工作缓存在内存缓存中。这是两全其美,您可以在不使用太多内存的情况下提高性能。

Even though a disk file is allocated for each temporary database, in practice the temporary database usually resides in the in-memory pager cache and hence is very little difference between a pure in-memory database created by ":memory:" and a temporary database created by an empty filename. The sole difference is that a ":memory:" database must remain in memory at all times whereas parts of a temporary database might be flushed to disk if database becomes large or if SQLite comes under memory pressure.

对您的应用程序进行概要分析和基准测试以确保它会带来性能改进,考虑优化查询和添加索引是否更好,并确保如果您的数据消失也没关系。