【问题标题】:JavaScript regexp performance.JavaScript 正则表达式性能。
【发布时间】:2011-03-16 11:46:18
【问题描述】:

我有一个函数可以纠正异常大写单词列表的大小写:

var line = "some long string of text";
["AppleScript", "Bluetooth", "DivX", "FireWire", "GarageBand", 
 "iPhone", "iTunes", "iWeb", "iWork", "JavaScript", "jQuery", "MacBook", 
 "MySQL", "PowerBook", "PowerPoint", "QuickTime", "TextEdit", "TextMate",
 // ... 
 "Wi-Fi", "Xcode", "Xserve", "XMLHttpRequest"].forEach(function(name) {
      line = line.replace(RegExp(name, "gi"), name);
});

现在我面临的问题是大多数输入字符串平均包含 0 到 3 个这些单词。显然,现在我正在执行数十个(可能还有数百个;随着时间的推移,该数组有一种不可思议的增长趋势)函数调用,这些函数调用基本上什么都不做。

我怎样才能使这段代码更快并摆脱不必要的函数调用?

示例输入:

我的 iphone 应用程序在 UIViewController 下有一个用户表单。当我再次启动应用程序时,我的一些 UIView 会更改其位置和大小。 (这些 UIViews 取决于键盘位置)某处绝对是我的错。我试图弄清楚当应用程序从后台再次启动时发生了什么以及 UIView 更改可以在哪里完成。

【问题讨论】:

  • 这些电话不是不必要的吗?如果您想检查每个字符串是否大写,那么您需要检查每个字符串...仅仅因为它不存在并不意味着不需要检查...
  • @Sam 但是在整个输入中是否有必要?或者可以设计一个更智能的正则表达式,在一个函数调用中完成所有检查?

标签: javascript regex performance


【解决方案1】:

您可以构建包含所有单词的正则表达式,通过将每个单词括在括号中来捕获它。在替换中使用它可以提供足够的信息来恢复替换函数中的原始单词。

  function correct (text, words) {
    return text.replace (RegExp ('\\b(?:(' + words.join (')|(') + '))\\b', 'ig'), function (m) {
      for (var a = arguments.length - 2; a--;)
        if (arguments[a])
      return words[a-1] || m;
    });
  } 

  console.log (correct ("My iphone itunes divx firewire application has a user form under uiviewcontroller. When I start application again some of my uiview changes its positions and sizes. (These uiviews depend on keyboard position) Somewhere is definitely my fault. I try to figure what is going on when application starts again from background and where the uiview changes can be done.",
    ["AppleScript", "Bluetooth", "DivX", "FireWire", "GarageBand", 
 "iPhone", "iTunes", "iWeb", "iWork", "JavaScript", "jQuery", "MacBook", 
 "MySQL", "PowerBook", "PowerPoint", "QuickTime", "TextEdit", "TextMate",
 // ... 
 "UIViewController","UIView",
 "Wi-Fi", "Xcode", "Xserve", "XMLHttpRequest"]));
My iPhone iTunes DivX FireWire application has a user form under UIViewController. When I start application again some of my UIView changes its positions and sizes. (These UIViews depend on keyboard position) Somewhere is definitely my fault. I try to figure what is going on when application starts again from background and where the UIView changes can be done.

This turns out to be faster then the original code.

【讨论】:

  • 这个函数调用的次数是 2 +(number_of_words_replaced)。其余的繁重工作由快速的内部函数完成。如果单词数组是静态的,则可以在每次调用时消除正则表达式构建
  • 正则表达式需要稍作修改,因为它会在单词中匹配:RegExp('\\b(?:(' + words.join(')|(') + '))\\b', 'ig') 就可以了。
  • 你是对的,我试过但被一对括号遗漏了;-)
  • @HBP 在 Chrome 和 Firefox 中进行了这些测试。 Firefox 与您的 Safari 运行相当,但 Chrome 显示您的代码要快得多。干得好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-16
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 2012-03-30
  • 2011-07-14
相关资源
最近更新 更多