📄 malloc.html
字号:
<p>The pBuf parameter is a pointer to a contiguous range of bytes thatSQLite will use for all scratch memory allocations. The buffer must beat least sz*N bytes in size. The "sz" parameteris the maximum size of each scratch allocation. N is the maximum number of simultaneous scratch allocations. The "sz" parameter shouldbe approximately 6 times the maximum database page size. N shouldbe the number of threads running in the system. No single thread willever request more than one scratch allocation at a time so if thereare never more than N threads, then there will always be enough scratchmemory available.</p><p>If the scratch memory setup does not define enough memory, thenSQLite falls back to using the regular memory allocator for its scratchmemory allocations. The default setup is sz=0 and N=0 so the useof the regular memory allocator is the default behavior.</p><a name="pagecache"></a><h3>3.3 Page cache memory</h3><p>In most applications, the database page cache subsystem within SQLite uses more dynamically allocated memory than all other partsof SQLite combined. It is not unusual to see the database page cacheconsumes over 10 times more memory than the rest of SQLite combined.</p><p>SQLite can be configured to make page cache memory allocations froma separate and distinct memory pool of fixed-sizeslots. This can have two advantages:</p><ul><li><p>Because allocations are all the same size, the memory allocator canoperate much faster. The allocator need not bother with coalescing adjacent free slots or searching for a slotof an appropriate size. All unallocated memory slots can be stored ona linked list. Allocating consists of removing the first entry from thelist. Deallocating is simply adding an entry to the beginning of the list.</p></li><li><p>With a single allocation size, the <b>n</b> parameter in the<a href="malloc.html#nofrag">Robson proof</a> is 1, and the total memory space required by the allocator(<b>N</b>) is exactly equal to maximum memory used (<b>M</b>). No additional memory is required to cover fragmentation overhead, thus reducing memory requirements. This is particularly important for thepage cache memory since the page cache constitutes the largest componentof the memory needs of SQLite.</p></li></ul><p>The page-cache memory allocator is disabled by default.An application can enabled it at start-time as follows:</p><blockquote><pre><a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_getmalloc.html">SQLITE_CONFIG_PAGECACHE</a>, pBuf, sz, N);</pre></blockquote><p>The pBuf parameter is a pointer to a contiguous range of bytes thatSQLite will use for page-cache memory allocations. The buffer must beat least sz*N bytes in size. The "sz" parameteris the size of each page-cache allocation. N is the maximum number of available allocations.</p><p>If SQLite needs a page-cache entry that is larger than "sz" bytes orif it needs more than N entries, it falls back to using thegeneral-purpose memory allocator.</p><a name="lookaside"></a><h3>3.4 Lookaside memory allocator</h3><p>SQLite <a href="c3ref/sqlite3.html">database connections</a> make manysmall and short-lived memory allocations.This occurs most commonly when compiling SQL statements using<a href="c3ref/prepare.html">sqlite3_prepare_v2()</a> but also to a lesser extent when running<a href="c3ref/stmt.html">prepared statements</a> using <a href="c3ref/step.html">sqlite3_step()</a>. These small memoryallocations are used to hold things such as the names of tablesand columns, parse tree nodes, individual query results values,and B-Tree cursor objects. There are consequentlymany calls to malloc() and free() - so many calls that malloc() andfree() end up using a significant fraction of the CPU time assignedto SQLite.</p><p>SQLite <a href="releaselog/3_6_1.html">version 3.6.1</a> introduced the lookaside memory allocator tohelp reduce the memory allocation load. In the lookaside allocator,each <a href="c3ref/sqlite3.html">database connection</a> preallocates a single large chunk of memory(typically in the range of 50 to 100 kilobytes) and divides that chunkup into small fixed-size "slots" of around 50 to 200 byte each. Thisbecomes the lookaside memory pool. Thereafter, memory allocationsassociated with the <a href="c3ref/sqlite3.html">database connection</a> and that are not too largerare satisfied using one of the lookaside pool slots rather than by callingthe general-purpose memory allocator. Larger allocations continue touse the general-purpose memory allocator, as do allocations that occurwhen the lookaside pool slots are all checked out. But in many cases, the memoryallocations are small enough and there are few enough outstanding thatthe new memory requests can be satisfied from the lookasidepool.</p><p>Because lookaside allocations are always the same size, the allocationand deallocation algorithms are very quick. There is noneed to coalesce adjacent free slots or search for a slotof a particular size. Each <a href="c3ref/sqlite3.html">database connection</a> maintains a singly-linkedlist of unused slots. Allocation requests simply pull the firstelement of this list. Deallocations simply push the element back ontothe front of the list.Furthermore, each <a href="c3ref/sqlite3.html">database connection</a> is assumed to already berunning in a single thread (there are mutexes already inplace to enforce this) so no additional mutexing is required to serialize access to the lookaside slot freelist.Consequently, lookaside memoryallocations and deallocations are very fast. In speed tests onLinux and Mac OS X workstations, SQLite has shown overall performanceimprovements as high as 10% and 15%, depending on the workload howlookaside is configured.</p><p>The size of the lookaside memory pool has a global default valuebut can also be configured on a connection-by-connection basis.To change the default size of the lookaside memory pool use the following interface at start-time:</p><blockquote><pre><a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_getmalloc.html">SQLITE_CONFIG_LOOKASIDE</a>, sz, cnt);</pre></blockquote><p>The "sz" parameter is the size in bytes of each lookaside slot.The default is 100 bytes. The "cnt" parameter isthe total number of lookaside memory slots per database connection.The default value is 500 slots. The total amountof lookaside memory allocated to each <a href="c3ref/sqlite3.html">database connection</a> issz*cnt bytes. Hence the lookaside memory pool allocated per database connection is 50 kilobytes by default.(Note: these default values are for SQLite <a href="releaselog/3_6_1.html">version 3.6.1</a> and are subjectto changes in future releases.)</p><p>The lookaside pool can be changed for an individual<a href="c3ref/sqlite3.html">database connection</a> "db" using this call:</p><blockquote><pre><a href="c3ref/db_config.html">sqlite3_db_config</a>(db, <a href="c3ref/c_dbconfig_lookaside.html">SQLITE_DBCONFIG_LOOKASIDE</a>, pBuf, sz, cnt);</pre></blockquote><p>The "pBuf" parameter is a pointer to memory space that will beused for the lookaside memory pool. If pBuf is NULL, then SQLitewill obtain its own space for the memory pool using <a href="c3ref/free.html">sqlite3_malloc()</a>.The "sz" and "cnt" parameters are the size of each lookaside slotand the number of slots, respectively. If pBuf is not NULL, then itmust point to at least sz*cnt bytes of memory.</p><p>The lookaside configuration can only be changed while there areno outstanding lookaside allocations for the database connection.Hence, the configuration should be set immediately after creating the database connection using <a href="c3ref/open.html">sqlite3_open()</a> (or equivalent) and beforeevaluating any SQL statements on the connection.</p><a name="memstatus"></a><h3>3.5 Memory status</h3><p>By default, SQLite keeps statistics on its memory usage. Thesestatistics are useful in helping to determine how much memory anapplication really needs. The statistics can also be used inhigh-reliability system to determineif the memory usage is coming close to or exceeding the limits of the <a href="malloc.html#nofrag">Robson proof</a> and hence that the memory allocation subsystem is liable to breakdown.</p><p>Most memory statistics are global, and therefore the tracking ofstatistics must be serialized with a mutex. Statistics are turned on by default, but an option exists to disable them. By disabling memory statistics,SQLite avoids entering and leaving a mutex on each memory allocationand deallocation. That savings can be noticeable on systems wheremutex operations are expensive. To disable memory statistics, thefollowing interface is used at start-time:</p><blockquote><pre><a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_getmalloc.html">SQLITE_CONFIG_MEMSTATUS</a>, onoff);</pre></blockquote><p>The "onoff" parameter is true to enable the tracking of memorystatistics and false to disable statistics tracking.</p><p>Assuming statistics are enabled, the following routine can be usedto access them:</p><blockquote><pre><a href="c3ref/status.html">sqlite3_status</a>(<a href="c3ref/c_status_malloc_size.html">verb</a>, ¤t, &highwater, resetflag);</pre></blockquote><p>The "verb" argument determines what statistic is accessed.There are <a href="c3ref/c_status_malloc_size.html">various verbs</a> defined. Thelist is expected to grow as the <a href="c3ref/status.html">sqlite3_status()</a> interface matures.The current value the selected parameter is written into integer "current" and the highest historical valueis written into integer "highwater". If resetflag is true, thenthe high-water mark is reset down to the current value after the callreturns.</p><p>A different interface is used to find statistics associated with asingle <a href="c3ref/sqlite3.html">database connection</a>:</p><blockquote><pre><a href="c3ref/db_status.html">sqlite3_db_status</a>(db, <a href="c3ref/c_dbstatus_lookaside_used.html">verb</a>, ¤t, &highwater, resetflag);</pre></blockquote><p>This interface is similar except that it takes a pointer toa <a href="c3ref/sqlite3.html">database connection</a> as its first argument and returns statistics aboutthat one object rather than about the entire SQLite library.The <a href="c3ref/db_status.html">sqlite3_db_status()</a> interface currently only recognizes asingle verb <a href="c3ref/c_dbstatus_lookaside_used.html">SQLITE_DBSTATUS_LOOKASIDE_USED</a>, though additional verbsmay be added in the future.</p><p>The per-connection statistics do not use global variables and hencedo not require mutexes to update or access. Consequently theper-connection statistics continue to function even if<a href="c3ref/c_config_getmalloc.html">SQLITE_CONFIG_MEMSTATUS</a> is turned off.</p><a name="heaplimit"></a><h3>3.6 Setting memory usage limits</h3><p>The <a href="c3ref/soft_heap_limit.html">sqlite3_soft_heap_limit()</a> interface can be used to set anupper bound on the total amount of outstanding memory that thegeneral-purpose memory allocator for SQLite will allow to be outstandingat one time. If attempts are made to allocate more memory that specifiedby the soft heap limit, then SQLite will first attempt to free cachememory before continuing with the allocation request. The soft heaplimit mechanism only works if <a href="malloc.html#memstatus">memory statistics</a> are enabled andif the SQLite library is compiled with the <a href="compile.html#enable_memory_management">SQLITE_ENABLE_MEMORY_MANAGEMENT</a>compile-time option.</p><p>The soft heap limit is "soft" in this sense: If SQLite is not ableto free up enough auxiliary memory to stay below the limit, it goesahead and allocations the extra memory and exceeds its limit. This occursunder the theory that it is better to use additional memory than to failoutright.</p><p>As of SQLite version 3.6.1, the soft heap limit only applies to thegeneral-purpose memory allocator. The soft heap limit does not knowabout or interact with the <a href="malloc.html#scratch">scratch memory allocator</a>, the <a href="malloc.html#pagecache">pagecache memory allocator</a>, or the <a href="malloc.html#lookaside">lookaside memory allocator</a>.This deficiency will likely be addressed in a future release.</p><a name="nofrag"></a><h2>4.0 Mathematical Guarantees Against Memory Allocation Failures</h2><p>The problem of dynamic memory allocation, and specifically theproblem of a memory allocator breakdown, has been studied byJ. M. Robson and the results published as:</p><blockquote>J. M. Robson. "Bounds for Some Functions Concerning DynamicStorage Allocation". <i>Journal of the Association forComputing Machinery</i>, Volume 21, Number 8, July 1974,pages 491-499.</blockquote><p>Let us use the following notation (similar but not identical toRobson's notation):</p>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -