在 Chrome 中分析我的网络应用程序时,我发现以下函数占用了我的应用程序总运行时间的很大一部分(考虑到它的使用频率,这是合理的 - 也许每个页面加载 1000 次)。因此,我想知道是否有人对如何改进以提高性能有任何建议?
function getDate(dateString) {
re = dateString.split(/\-|\s/);
return new Date(re.slice(0, 3).join('/') + ' ' + re[3]);
}
此函数给出一个格式为“YYYY-MM-DD HH:MM:SS”的字符串,例如:“2014-06-06 23:45:00”,并返回一个 Javascript 日期。
我正在使用 jQuery,所以这是一个选项。
最佳答案
检查以下代码:
function getDate(dateString) {
re = dateString.split(/\-|\s/);
return new Date(re.slice(0, 3).join('/') + ' ' + re[3]);
}
function getDate2(d) {
return new Date(
d.substr(0, 4) +
'/' +
d.substr(5, 2) +
'/' +
d.substr(8, 2) +
' ' +
d.substr(11, 8)
);
}
function getDate3(d) {
return new Date(d);
}
function benchmark(func, times) {
var start = new Date();
for (var i = 0; i < times; i++) {
var temp = eval(func);
}
var end = new Date();
console.log(func + 'took ' + (end - start) + ' microseconds to execute ' + times + ' times.');
}
var str = '2014-06-06 23:45:15';
benchmark("getDate(str)", 1000000);
benchmark("getDate2(str)", 1000000);
benchmark("getDate3(str)", 1000000);
这给了我以下结果:
LOG: getDate(str)took 2215 microseconds to execute 1000000 times.
LOG: getDate2(str)took 940 microseconds to execute 1000000 times.
LOG: getDate3(str)took 270 microseconds to execute 1000000 times.
因此,您可以看到正则表达式引擎在 Javascript 中受到了很高的惩罚。使用 substr
将执行时间减少了 50% 以上,而使用直接字符串(在现代 Javascript 运行时中有效)将执行时间减少了近 90%。 :-)
关于javascript - 有什么方法可以使这个功能在标准浏览器中更有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24101130/