Memory management when using sqlite database in iphone

前端 未结 6 1213
我在风中等你
我在风中等你 2021-02-03 16:18

My application makes use of a SQLite database to store the user\'s inputs. The number of records in the input would go to around 100 records and I have a lot of SQL operations g

相关标签:
6条回答
  • 2021-02-03 16:33

    I've seen memory usage spike before when I had a relatively large database because of poor indexing. If you add a few well thought out indexes to your database, it is a quick and easy way to get memory usage back in the real world.

    0 讨论(0)
  • 2021-02-03 16:37

    You really want to limit the cache size of sqlite in iphone applications. When you launch your application and initialize your database run a command like:

    const char *pragmaSql = "PRAGMA cache_size = 50";
    if (sqlite3_exec(database, pragmaSql, NULL, NULL, NULL) != SQLITE_OK) {
        NSAssert1(0, @"Error: failed to execute pragma statement with message '%s'.", sqlite3_errmsg(database));
    }
    

    this will prevent sqlite from caching your queries and slowly consuming all of your memory.

    0 讨论(0)
  • 2021-02-03 16:43

    Sqlite uses a cache for requests. Close & reopen the database from time to release cache memory.

    You shouldnt care unless your memory requirements are high.

    You can catch critical conditions in the UIApplicationDelegate method applicationDidReceiveMemoryWarning or UIViewController delegate method didReceiveMemoryWarning

    If one of these methods is called, close & reopen the database.

    0 讨论(0)
  • 2021-02-03 16:43

    There are also PRAGMAs to modify the cache size.

    0 讨论(0)
  • 2021-02-03 16:52

    I've had memory usage shoot up in SQLite when doing many INSERTs (> 1000) in a row. Write performance was also slow. These issues were almost completely eliminated by wrapping the loop doing the INSERTs in a transaction. I posted some sample code for this in response to this question.

    0 讨论(0)
  • 2021-02-03 16:57

    I've not seen any memory leaks caused by sqlite. It does use a reasonable chunk of memory, but think of how much code you'd need to write and data you'd need to cache to do the same thing...

    The best advice is to use efficient SQL and reset your statement handles as soon as possible. Finalizing your prepared statements might also help, though I've not found the need to do that.

    People often recommend periodically closing and reopening the database. While this won't hurt I've not seen any practical benefit myself.

    Finally, on the sqlite website you'll see talk of functions to manage memory. These sound quite seductive until you realise they're optional and are not enabled in the default build on the iPhone.

    0 讨论(0)
提交回复
热议问题