巧用局部变量提升javascript性能
时间:2024-04-18 09:33:19
javascript中一个标识符所在的位置越深,它的读写速度也越慢。因此,函数中读写局部变量总是最快的,而读写全局变量通常是最慢的。一个好的经验法则是:如果某个跨作用域的值在函数中被引用一次以上,那么就把它存储到局部变量里。
例如:
<!-- 优化前 -->
<script type="text/javascript">
function initUI () {
var bd = document.body,
links = document.getElementByTagName("a"),
i=0,
len=links.length;
while(i < len){
update(links[i++]);
}
document.getElementById("go-btn").onclick = function(){
start();
}
bd.className = "active";
}
</script>
该函数引用了三次document,而document是个全局对象。搜索该变量的过程必须遍历整个作用域链接,直到最后在全局变量对象中找到。你可以通过以下方法减少对性能的影响:先将全局变量的引用存储在一个局部变量中,然后使用这个局部变量代替全局变量。
例如:
<!-- 优化后 -->
<script type="text/javascript">
function initUI () {
var doc=document,
bd = doc.body,
links = doc.getElementByTagName("a"),
i=0,
len=links.length;
while(i < len){
update(links[i++]);
}
doc.getElementById("go-btn").onclick = function(){
start();
}
bd.className = "active";
}
</script>
标签:局部变量,提升性能
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL学习笔记5:修改表(alter table)
2024-01-23 23:01:16
Flask表单与表单验证实现流程介绍
2024-01-02 05:05:45
![](https://img.aspxhome.com/file/2023/2/64632_0s.png)
macOS Sierra安装Apache2.4+PHP7.0+MySQL5.7.16
2023-11-15 13:05:39
![](https://img.aspxhome.com/file/2023/5/78105_0s.jpg)
web程序员的思考
2009-08-04 13:10:00
使用php-timeit估计php函数的执行时间
2023-10-07 19:56:50
实例学习call、apply、callee用法
2009-03-27 17:56:00
使用python执行shell脚本 并动态传参 及subprocess的使用详解
2021-05-30 22:46:49
![](https://img.aspxhome.com/file/2023/2/118582_0s.jpg)
详解基于webpack&gettext的前端多语言方案
2024-04-16 09:52:34
使用 vue-i18n 切换中英文效果
2024-04-27 16:17:40
![](https://img.aspxhome.com/file/2023/6/132926_0s.jpg)
python tqdm库的使用
2023-10-30 22:32:44
![](https://img.aspxhome.com/file/2023/9/131009_0s.png)
jQuery.data()方法与内存泄漏
2010-04-06 17:20:00
![](https://img.aspxhome.com/file/UploadPic/20104/6/01-17s.jpg)
利用matplotlib+numpy绘制多种绘图的方法实例
2021-02-24 14:10:07
![](https://img.aspxhome.com/file/2023/4/123464_0s.png)
python抓取京东商城手机列表url实例代码
2022-11-11 18:23:04
PHP实现的注册,登录及查询用户资料功能API接口示例
2024-04-30 08:50:18
现代Python编程的四个关键点你知道几个
2023-11-22 02:17:42
![](https://img.aspxhome.com/file/2023/1/64601_0s.jpg)
使用Python中PIL库给图片添加文本水印
2021-09-07 19:09:52
![](https://img.aspxhome.com/file/2023/9/110029_0s.jpg)
什么是DOM(Document Object Model)文档对象模型
2024-05-13 09:37:04
GO中的条件变量sync.Cond详解
2024-02-10 15:08:35
Hibernate 的原理与配置
2023-07-20 21:26:52
python基于Node2Vec实现节点分类及其可视化示例详解
2022-04-16 06:49:33