代码之家  ›  专栏  ›  技术社区  ›  Thomas David Kehoe

regex使Angular编译变得超级慢

  •  0
  • Thomas David Kehoe  · 技术社区  · 3 年前

    Angular不会编译一个有142个正则表达式的服务。前五十个还可以,但每增加一个正则表达式都会减慢编译速度。它停在77( Generating browser application bundles... )。

    该服务将西班牙语单词转录成国际音标(IPA)。这是一个代码示例。

    // Rule 12, 'v'
      // if the word includes 'v'
      if (word.includes('v')) {
        rulesArray.push('12');
    
        // if 'v' is the first letter
        if (word.charAt(0) === 'v') {
          ipaWord = ipaWord.replace('v', '7'); // replace 'v' with '7'
        }
    
        // if word includes 'mv'
        if (word.includes('mv')) {
          regexp = /mv/gi
          ipaWord = ipaWord.replace(regexp, 'm7'); // replace 'mv' with 'm7'
        }
    
        // if word includes 'nv'
        if (word.includes('nv')) {
          regexp = /nv/gi
          ipaWord = ipaWord.replace(regexp, 'n7');  // replace 'nv' with 'n7'
        }
    
        regexp = /v/gi
        ipaWord = ipaWord.replace(regexp, 'β'); // replace 'v' with 'β' in all other cases
    
        regexp = /7/gi
        ipaWord = ipaWord.replace(regexp, 'b');  // restore 'b'
      } // close Rule 12, if the word includes 'v'
    

    几年前,我为Firebase的Cloud Functions编写了这段代码,在那里运行得很好。我只是想,通过将其作为Angular(同步)中的服务,而不是调用云函数(异步),我可以保存一个网络调用,并使我的应用程序运行得更快。

    是我做错了什么,还是Angular讨厌正则表达式?

    活动监视器显示CPU空闲65%,内存压力低,能量、磁盘和网络活动低。我听到风扇在使劲运转,我能感觉到电脑很热。有没有办法使用Chrome开发工具来查看哪些代码被停止了?

    Visual Studio代码对同一文件有问题。原始文件是JavaScript,我正在将其转换为TypeScript,这需要在顶部声明变量。当变量在顶部声明时,VSCode会抛出错误,表示变量尚未声明。退出并重新启动TypeScript可以修复错误。

    如果我是个天才,我可能会将142个正则表达式重写为一个超级正则表达式,但其他人无法读取。

    0 回复  |  直到 3 年前
        1
  •  0
  •   Thomas David Kehoe    3 年前

    我把文件分成十六个文件,解决了这个问题。

        word = spanishPhonologyRule1(word) as string;
        word = spanishPhonologyRule13(word) as string;
        word = spanishPhonologyRule12(word) as string;
        word = spanishPhonologyRule2(word, shortAccent) as string;
        word = spanishPhonologyRule3(word) as string;
        word = spanishPhonologyRule4(word) as string;
        word = spanishPhonologyRule11(word) as string;
        word = spanishPhonologyRule5(word) as string;
        word = spanishPhonologyRule6(word) as string;
        word = spanishPhonologyRule7(word) as string;
        word = spanishPhonologyRule8(word) as string;
        word = spanishPhonologyRule9(word) as string;
        word = spanishPhonologyRule10(word) as string;
        word = spanishPhonologyRule14(word, shortAccent) as string;
        word = spanishPhonologyRule15(word, shortAccent) as string;
    

    我试图将文件移动到Firebase的Cloud Functions,但编译器速度减慢,也停止了。在Cloud Functions中编译的原始JavaScript文件没有问题。问题似乎是,当JavaScript在不减慢速度的情况下编译100多个正则表达式时,TypeScript无法编译超过60或70个正则表达式。

    推荐文章