sqlite3 内存持续增加_如何减少SQLite内存消耗?

本文探讨了如何减少SQLite内存消耗,包括使用预编译语句,调整事务大小,启用EXCLUSIVE锁定模式,调整缓存大小,考虑temp_store设置,并利用PRAGMA指令如shrink_memory和vacuum。此外,还建议避免在INTEGER PRIMARY KEY上创建额外索引,以提高INSERT、DELETE和UPDATE操作的速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我会:

>准备语句(如果你没有这样做)

>降低每个事务的INSERT数量(10秒= 50万个声音适当)

>使用PRAGMA locked_mode = EXCLUSIVE;如果你可以的话

另外,(我不知道如果你知道)PRAGMA cache_size是页面,而不是MB.确保将目标内存定义为PRAGMA cache_size * PRAGMA page_size或在SQLite> = 3.7.10中,还可以执行PRAGMA cache_size = -kibibytes ;.将其设置为1 M(illion)将导致1或2 GB.

我很好奇cache_size如何帮助INSERT,虽然…

如果PRAGMA temp_store = FILE,您还可以尝试和基准测试;有所作为

当然,当你的数据库没有被写入时:

> PRAGMA shrink_memory;

>真空;

根据您在使用数据库的方式,这些可能还有助于:

> PRAGMA auto_vacuum = 1 | 2;

> PRAGMA secure_delete = ON;

我用以下pragmas进行了一些测试:

busy_timeout=0;

cache_size=8192;

encoding="UTF-8";

foreign_keys=ON;

journal_mode=WAL;

legacy_file_format=OFF;

synchronous=NORMAL;

temp_store=MEMORY;

测试#1:

INSERT OR IGNORE INTO test (time) VALUES (?);

UPDATE test SET count = count + 1 WHERE time = ?;

每秒钟播放〜109k更新.

测试#2:

REPLACE INTO test (time, count) VALUES

(?, coalesce((SELECT count FROM test WHERE time = ? LIMIT 1) + 1, 1));

每秒钟以〜120k的更新速度.

我也尝试过PRAGMA temp_store = FILE;更新下降了约1-2k每秒.

对于事务中的7M更新,journal_mode = WAL比所有其他更慢.

我填充了35,839,987条记录的数据库,现在我的安装程序每批65521次更新需要近4秒的时间,但是它甚至不能达到16 MB的内存消耗.

好的,这是另一个:

Indexes on INTEGER PRIMARY KEY columns (don’t do it)

When you create a column with INTEGER PRIMARY KEY, SQLite uses this

column as the key for (index to) the table structure. This is a hidden

index (as it isn’t displayed in SQLite_Master table) on this column.

Adding another index on the column is not needed and will never be

used. In addition it will slow INSERT, DELETE and UPDATE operations

down.

您似乎将PK定义为NOT NULL UNIQUE. PK是UNIQUE隐含的.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值