JavaScript正则表达式性能。

JavaScript正则表达式性能。,javascript,regex,performance,Javascript,Regex,Performance,我有一个函数,可以修正一系列不寻常的大写单词的大写: var line = "some long string of text"; ["AppleScript", "Bluetooth", "DivX", "FireWire", "GarageBand", "iPhone", "iTunes", "iWeb", "iWork", "JavaScript", "jQuery", "MacBook", "MySQL", "PowerBook", "PowerPoint", "QuickTim

我有一个函数,可以修正一系列不寻常的大写单词的大写:

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会更改其位置和大小。(这些视图取决于键盘位置)某个地方肯定是我的错。我试图弄清楚当应用程序再次从后台启动时发生了什么,UIView的更改可以在哪里进行


您可以构建包含所有单词的regexp,通过将每个单词括在括号中来捕获它。在replace中使用它将提供足够的信息,以便在replace函数中恢复原始字

  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.

.

这些电话不是不必要的,是吗?如果要检查每个字符串是否大写,则需要检查每个字符串。。。仅仅因为它不存在,并不意味着检查是不必要的…@Sam,但对整个输入是必要的?或者可以设计一个更智能的regexp,在一个函数调用中完成所有检查吗?这样做的函数调用数为2+(替换的单词数)。其余的重型提升由快速内部功能完成。如果单词数组是静态的,您可以在每次调用时消除regexp构建。regexp需要稍微修改,因为它随后在单词中匹配:
regexp('\\b(?('+words.join(')|)(')+')\\b','ig')
就可以了。您是对的,我尝试过了,但被一对括号遗漏了;-)@HBP在Chrome和Firefox中运行了这些测试。Firefox与您的Safari运行相当,但Chrome显示您的代码要快得多。干得好!