前端性能优化(六)01-页面性能优化之优化工具——JsPerf代码性能对比工具 & moment().format()-时间组件
代码优化——写出优质的代码
命题很大,但是我们要简化来谈一下。
代码优化,先要写出优质的代码,有几点原则:
- 使用辅助应用对代码进行检查,Eslint等
- 使用预编译工具,如less,sass,stylus。
- 使用官方的开发规范:命名规范、注释、使用规范、文档规范
- 写出逻辑上易于阅读的代码:设计模式、代码结构、文档编排(目录结构)
- 代码审查
- 单元测试
- 异常与错误机制
之后就是练习与阅读,阅读别人的代码,学习别人的精华,了解别人代码中的缺点。使用JsPerf或者benchemark去对比优化性能。
前端代码规范:Airbnb,github,Google,腾讯,阿里等。
JsPerf
JsPerf在线:https://jsperf.com/
JsPerf Github地址:https://github.com/jsperf/jsperf.com
JsPerf使用简介
线上使用方案
需要使用Github进行登录:
点击Login with Github to Create Test Cases
:
登录之后,进入授权页面:
登录过后,就可以创建自己的测试用例啦:
线下使用方案:
环境准备:
- Mysql
- Nodejs
创建过程:
-
安装Mysql
mysql -uroot -e "CREATE DATABASE jsperf; GRANT ALL ON jsperf.* TO 'jsuser'@'localhost' IDENTIFIED BY 'jspass'; FLUSH PRIVILEGES;"
-
在 Browserscope.org 注册一个API key ,在 the settings page页面中.
-
注册一个 new OAuth GitHub application. 使用callback URL 留空. 复制 “Client ID” 和 "Client Secret"到github的页面上。
-
使用
npm install
安装 -
配置
.env
的文件
NODE_ENV=development
# from Prerequisites step 1
MYSQL_USER=jsuser
MYSQL_PASSWORD=jspass
MYSQL_DATABASE=jsperf
# from Prerequisites step 2
BROWSERSCOPE=
# from Prerequisites step 3
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GITHUB_CALLBACK=http://localhost:3000
BELL_COOKIE_PASS=password-should-be-32-characters
COOKIE_PASS=password-should-be-32-characters
# customizable but not recommended for local development
# SCHEME=http
# DOMAIN=localhost
# PORT=3000
# MYSQL_HOST=localhost
# MYSQL_PORT=3306
# LOGGLY_TOKEN=
# LOGGLY_SUBDOMAIN=
# REDIS_HOST=
# REDIS_PORT=
# REDIS_PASSWORD=
- 运行
npm start
代码示例for vs foreach
我们对比一下for 与 foreach
测试过程:
测试结果:
这里有一个更全面的对比结果:
https://jsperf.com/for-vs-foreach/75
还有一些比较有意思的测试:
可以通过浏览:https://jsperf.com/popular进行查看
前端项目优化实践
效果
我们来对比下Date()与Moment()中的format
http://momentjs.cn/docs/#/displaying/
const Benchmark = require('benchmark');
const moment = require('moment')
Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
return fmt;
}
var suite = new Benchmark.Suite;
// add tests
suite.add('Date format', function () {
console.log(new Date().Format('yyyy-MM-dd hh:mm:ss'))
})
.add('Moment format', function () {
console.log(moment().format('YYYY-MM-DD HH:mm:ss'))
})
// add listeners
.on('cycle', function (event) {
console.log(String(event.target));
})
.on('complete', function () {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });
输出结果 :
Moment format x 73,570 ops/sec ±4.93% (82 runs sampled)
Fastest is Moment format