javascript - 有什么方法可以使这个功能在标准浏览器中更有效吗?

标签 javascript jquery performance

在 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/

相关文章:

javascript - 在 highcharts 中导出时如何添加图像?

javascript - 如何使用 PHP 比较 Selenium WebDriver 中元素的位置

javascript - 之后隐藏 Bootstrap 折叠触发按钮

jquery - 网页开发 - 整个 "scalable"网站没有 flash,可能吗?

jquery - 获取动态id以在jquery ajax中显示信息

javascript - Chart.js - 将折线图格式数据转换为 Lacs/Crores

java - removeAll ArrayList 与 LinkedList 性能

数据库:多张表还是只有一张表?

performance - Scala 中的高效字符串连接

javascript - 将文档对象传递给函数