![](/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.