在大多数情况下,你可以通过计算磁盘寻道次数来估算查询性能。对于小表,你通常可以在一次磁盘寻道中找到一行(因为索引可能已经被缓存)。对于大表,你可以估算使用 B 树索引时找到一行所需的寻道次数:log(row_count) /
log(index_block_length / 3 * 2 /
(index_length +
data_pointer_length)) + 1。In most cases, you can estimate query performance by counting
disk seeks. For small tables, you can usually find a row in one
disk seek (because the index is probably cached). For bigger
tables, you can estimate that, using B-tree indexes, you need
this many seeks to find a row:
log(.row_count) /
log(index_block_length / 3 * 2 /
(index_length +
data_pointer_length)) + 1
在 MySQL 中,一个索引块通常为 1,024 字节,数据指针通常为四个字节。对于一个有 500,000 行且键值长度为三个字节(MEDIUMINT 大小)的表,公式表明 log(500,000)/log(1024/3*2/(3+4)) + 1 = 4 次查找。In MySQL, an index block is usually 1,024 bytes and the data
pointer is usually four bytes. For a 500,000-row table with a
key value length of three bytes (the size of
MEDIUMINT), the formula indicates
log(500,000)/log(1024/3*2/(3+4)) + 1 =
4 seeks.
该索引大约需要存储 500,000 * 7 * 3/2 = 5.2MB(假设典型的索引缓冲区填充率为 2/3),所以你可能有大部分索引在内存中,因此只需要一到两次调用即可读取数据以找到行。This index would require storage of about 500,000 * 7 * 3/2 = 5.2MB (assuming a typical index buffer fill ratio of 2/3), so you probably have much of the index in memory and so need only one or two calls to read data to find the row.
然而,对于写操作,你需要四次寻道请求来找到放置新索引值的位置,通常还需要两次寻道来更新索引并写入行。For writes, however, you need four seek requests to find where to place a new index value and normally two seeks to update the index and write the row.
前面的讨论并不意味着您的应用性能会以 log N 的速度缓慢下降。只要操作系统或 MySQL 服务器缓存了一切,随着表的增大,性能仅会略微下降。当数据过大无法被缓存时,性能会显著下降,直到您的应用完全受磁盘寻道限制(磁盘寻道按 log N 增加)。为了避免这种情况,随着数据增长增加键缓存大小。对于 MyISAM 表,键缓存大小由 key_buffer_size 系统变量控制。参见 第 7.1.1 节,“配置服务器”。The preceding discussion does not mean that your application
performance slowly degenerates by log
N. As long as everything is cached by
the OS or the MySQL server, things become only marginally slower
as the table gets bigger. After the data gets too big to be
cached, things start to go much slower until your applications
are bound only by disk seeks (which increase by log
N). To avoid this, increase the key
cache size as the data grows. For MyISAM
tables, the key cache size is controlled by the
key_buffer_size system
variable. See Section 7.1.1, “Configuring the Server”.