• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

JavaScript字符串相等性能比较

用户头像
it1352
帮助1

问题说明

我有一个noob javascript问题。假设我们有两个非常大的字符串(〜百万字符或更多)是相同的 - 它们具有相同的长度和相同的内容。
假设我们有这两个函数都做同样的事情(比较字符串):

I have a noob javascript question. Let's say we have two very large strings (~ million characters or more) that are equal - they have the same length and the same content. Let's say we have these two function that both do the same thing (compare strings):

function equals1(a, b) {
    return a === b;
}

function equals2(a, b) {
    if (a.length !== b.length) {
           return false;
    }
    for (var i = 0; i < a.length;   i) {
        if (a[i] !== b[i]) {
            return false;
         }
    }
    return true;
}

为什么第一个函数(equals1())的速度几乎是第二个?
如何改进第二个,使其表现与第一个一样好?

Why is the first function (equals1()) almost as twice as fast as the second one? How can the second one be improved so that it performs as good as the first one?

正确答案

#1

第一个做同样的事情。如果字符串长度不同,则返回false。然后它检查相同索引处的字符是否相同。但是,它是在JS实现级别实现的,因此它的运行速度与C,C ,Java或编写JavaScript实现的任何语言一样快。

The first does the same things. If the strings are different lengths, it will return false. Then it checks to see if the characters are the same at the same indices. However, it is implemented at the JS implementation level, so it is running as fast as C, C , Java or whatever language the JavaScript implementation is written in.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfgchb
系列文章
更多 icon
同类精品
更多 icon
继续加载