简体   繁体   English

如何改善此元音计数器功能以获得更高的效率?

[英]How can I improve this vowel counter function for higher efficiency?

This code works, but I was wondering if it was possible to receive some advice on how to make this function run faster. 该代码有效,但我想知道是否有可能收到有关如何使此函数运行更快的建议。

I have used regular expressions as well as the match method because they seem straightforward to me. 我使用了正则表达式以及match方法,因为它们对我而言似乎很简单。

const vowelCount = str => {
  let vowels = /[aeiou]/gi;
  let result = str.match(vowels);
  let count = result.length;

  console.log(count);
};

The function will display the number of vowels inside a string. 该函数将显示字符串中的元音数量。

A simple for loop or foreach is marginally faster but it is so minor that you aren't really looking at much benefit by moving here. 简单的for循环或foreach速度稍快,但是它很小,因此您搬到这里并没有看到太多好处。

However here are some faster options. 但是,这里有一些更快的选择。

Your Code (timed): ~0.185 ms 您的代码(定时):〜0.185 ms

 const vowelCount = str => { let vowels = /[aeiou]/gi; let result = str.match(vowels); return result.length; }; var t0 = performance.now(); vowelCount("aSdDDDdasDD"); var t1 = performance.now(); console.log("Call took: " + (t1 - t0) + " MS"); 


For-Loop (timed): ~.070 ms 前循环(定时):〜.070毫秒

 const vowelCount = str => { var vowels = 'aeiouAEIOU'; var count = 0; for(var x = 0; x < str.length ; x++) { if (vowels.indexOf(str[x]) !== -1){ count += 1; } } return count; }; var t3 = performance.now(); vowelCount("aSdDDDdasDD"); var t4 = performance.now(); console.log("Call took: " + (t4 - t3) + " MS"); 


For-Each (timed): ~.074 ms 每次(定时):〜.074毫秒

 const vowelCount = str => { var vowels = 'aeiouAEIOU'; var count = 0; Array.from(str).forEach((c) => { if(vowels.indexOf(c)) { count++; } }); return count; }; var t3 = performance.now(); vowelCount("aSdDDDdasDD"); var t4 = performance.now(); console.log("Call took: " + (t4 - t3) + " MS"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM