Skip to content

Commit a8987bf

Browse files
committed
Periodically flush the database on creation
Reduces memory usage by about 80% when creating the database, for a slightly higher runtime
1 parent 123dd83 commit a8987bf

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/db.c

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
#define DB_ID_TO_DEFINITIONS "db2"
1313
#define DB_FREQUENCIES "db3"
1414
#define DB_METADATA "db4"
15+
#define FLUSH_THRESHOLD 10000
16+
static int write_count = 0;
1517

1618
DEFINE_DROP_FUNC(MDB_cursor *, mdb_cursor_close)
1719

@@ -110,6 +112,18 @@ database_t *db_open(bool readonly) {
110112
return readonly ? db_open_readonly() : db_open_read_write();
111113
}
112114

115+
static void db_flush(database_t *db) {
116+
if (!db || db->readonly) {
117+
return;
118+
}
119+
120+
int rc = mdb_txn_commit(db->txn);
121+
if (rc != MDB_SUCCESS) {
122+
dbg("Error committing transaction: %s", mdb_strerror(rc));
123+
}
124+
MDB_CHECK(mdb_txn_begin(db->env, NULL, 0, &db->txn));
125+
}
126+
113127
void db_close(database_t *db) {
114128
if (!db)
115129
return;
@@ -168,6 +182,14 @@ static void add_key_with_id(database_t *db, s8 key, u32 id) {
168182
mdb_put(db->txn, db->db_words_to_id, &key_mdb, &id_mdb, MDB_NODUPDATA);
169183
}
170184

185+
static void increase_write_count(database_t *db) {
186+
write_count++;
187+
if (write_count >= FLUSH_THRESHOLD) {
188+
db_flush(db);
189+
write_count = 0;
190+
}
191+
}
192+
171193
void db_put_dictent(database_t *db, Dictentry de) {
172194
die_on(db->readonly, "Cannot put dictentry into db in readonly mode.");
173195
if (!de.definition.len) {
@@ -184,6 +206,8 @@ void db_put_dictent(database_t *db, Dictentry de) {
184206
put_de_if_new(db, de);
185207
add_key_with_id(db, de.kanji, db->last_id);
186208
add_key_with_id(db, de.reading, db->last_id);
209+
210+
increase_write_count(db);
187211
}
188212

189213
static u32 *get_ids(const database_t *db, s8 word, size_t *num) {

0 commit comments

Comments
 (0)