每个程序员应该有一把尺子,这个尺子就是各种语句执行的开销.
今天在网络上搜到了一些有趣的order magnitude
- 美国东海岸-西海岸的时间(network): 60ms
- Relative Data Access Latency Fast Slow
- CPU Registers (1)
- L1 Cache (1-2)
- L2 Cache (6-10)
- Main Memory (25-100)
- Hard drive(1e7)
- LAN(1e7-1e8)
- WAN(1e9-2e9)
CPU Registers 比内存快100倍
内存比磁盘快1万倍
磁盘比内网快10倍
内网比外网快10倍
- Relative Data Access Latency Fast Slow
- CPU寄存器:人类平均升高
- RAM : 25 ~ 100 Godzilla 哥斯拉
- Hard Drive: 10M 0.4 地球赤道一周
- WAN: 100M 0.42地球到月球
- Mobile phone (iphone 3G 500ms): 500M 地球月球往返
提高响应速度的策略
- move date up 网络
- make fewer http request(避免从地球到月球)
- 使用CDN(content delivery network)
- Add an expires header(climb 哥斯拉[RAM] instead of 去月球[network]
- 使用压缩格式,Gzip
- move date up 磁盘
- Bloom Filter来检查是否元素存在,从而避免不必要的磁盘操作
- 将索引放在内存(压缩,再压缩)
- 顺序读写代替随机读写
- 使用批量(batching) 和流式(streaming)
- 保持数据的局部性(locality)
- move date up 内存 cache line awareness
- Linked List 不要一次分配一个节点
- Hash table 冲突再探测,使用步长为1 (?)
- stack allocation :栈的顶部放在cache中,堆不是
- Pipeline processing 流水线处理,each stage separately
- Optimize for size 好的cache size 比好的code快
- 实际优化
- Memcached Facebook: 使用UDP代替TCP,减少packet; batch deque减少锁竞争。20万/s请求,平均0.173毫秒
浏览器时间:
Fetch time
Parse time (html css javascript)
Execution time(javascript execution, DOM construction and layout, style application)
参考:
Steve Souders: High performance web sites