![](/img/trans.png)
[英]What's the best/fastest way to recognize if a string number is exactly representable in floating point (or double)?
[英]What's the best/fastest way to find the number of tabs to start a string?
我想在字符串的开头找到制表符的数量(当然,我希望它是快速运行的代码;))。 这是我的主意,但不确定这是最佳/最快的选择:
//The regular expression
var findBegTabs = /(^\t+)/g;
//This string has 3 tabs and 2 spaces: "<tab><tab><space>something<space><tab>"
var str = " something ";
//Look for the tabs at the beginning
var match = reg.exec( str );
//We found...
var numOfTabs = ( match ) ? match[ 0 ].length : 0;
另一种可能性是使用循环和charAt:
//This string has 3 tabs and 2 spaces: "<tab><tab><space>something<space><tab>"
var str = " something ";
var numOfTabs = 0;
var start = 0;
//Loop and count number of tabs at beg
while ( str.charAt( start++ ) == "\t" ) numOfTabs++;
通常,如果您可以通过简单地遍历字符串并在每个索引处进行字符检查来计算数据,则这将比正则表达式更快,而正则表达式会建立更复杂的搜索引擎。 我鼓励您对此进行简介,但我认为您会发现直接搜索更快。
注意:您的搜索应在此处使用===
而不是==
,因为您无需在相等性检查中引入转换
function numberOfTabs(text) {
var count = 0;
var index = 0;
while (text.charAt(index++) === "\t") {
count++;
}
return count;
}
尝试使用探查器 (例如jsPerf或许多可用的后端探查器之一 )在目标系统(您计划支持软件的浏览器和/或解释器 )上创建和运行基准测试。
根据您的预期数据和目标系统来推断哪种解决方案将表现最佳是很有用的; 但是,您有时可能会对哪种解决方案的执行速度最快感到惊讶,特别是在大数据分析和典型数据集方面。
在您的特定情况下,迭代字符串中的字符可能比使用正则表达式操作更快。
一线(如果您发现最小最好):
"\t\tsomething".split(/[^\t]/)[0].length;
例如,将所有非制表符分开,然后获取第一个元素并获取其长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.