[英]Efficiency of int vs int[]
目前,我有一個正在編寫的郵政編碼驗證程序,並且已聲明和命名了6個整數變量,並根據該郵政編碼與良好的郵政編碼標准相匹配的程度進行了適當的命名。 擁有6個整數使我能夠以一種很容易看到的方式命名每個整數。 但是,如果我要使用整數數組來存儲這些計數,那么我編寫的代碼可能會更加整潔,因為我發現我不得不用if語句來解釋,以便從regex_match中獲得我發現的那個整數增加。
例如,我目前寫過:
for(int iteration = 0 ; iteration < 6 ; iteration++) {
expression = testStrings[iteration];
if(std::regex_match(toTest, expression)) {
if(iteration == 0) return FullMatch; //place 0 match = Good UK Postcode
if(iteration == 1) return SyntaxFail; //place 1 match = Poor UK Postcode
if(iteration == 2) return ZipCodeFail; //place 2 match = Zipcode
if(iteration == 3) return IrelandFail; //place 3 match = Ireland
if(iteration == 4) return IrelandFail; //place 4 match = Alternate Ireland
if(iteration == 5) return CanadaFail; //place 5 match = Canada
}
}
但這可以假設為:
for(int iteration = 0 ; iteration < 6 ; iteration++) {
expression = testStrings[iteration];
if(std::regex_match(toTest, expression)) {
return PostcodeCount[iteration]
}
或類似的原因,說明我已經檢查了兩種不同的愛爾蘭地址方式。
我編寫的代碼中還有其他地方目前是明確的,但可以使用數組來縮短編寫的代碼量,但要付出少量可讀性。
目前,我的程序可以正常運行,並且可以完成我想做的所有事情,但是我想一次使用此代碼來驗證大約30,000個郵政編碼,因此,我希望它比目前的效率更高(盡管這並不意味着當前需要花費幾英畝的時間)。 如果效率提高很少或沒有,我不想犧牲太多的可讀性。
我曾嘗試向Google尋求此問題的答案,但今晚我的Google-fu一定很弱,因為我只發現了關於向量和數組相對效率的網絡參考,對於我想知道的東西一無所獲。
兩種解決方案之間的差異可以忽略不計。 無論如何, regex_match
調用可能會更加昂貴。 順便說一句,您的代碼要求使用switch
語句。
if(std::regex_match(toTest, testStrings[0])) return FullMatch; //Good UK
if(std::regex_match(toTest, testStrings[1])) return SyntaxFail; //Poor UK
if(std::regex_match(toTest, testStrings[2])) return ZipCodeFail; //Zipcode
if(std::regex_match(toTest, testStrings[3])) return IrelandFail; //Ireland
if(std::regex_match(toTest, testStrings[4])) return IrelandFail; //Alt Ireland
if(std::regex_match(toTest, testStrings[5])) return CanadaFail; //Canada
我將更進一步,只使用命名變量而不是該正則表達式數組。
無論您采用哪種方式,性能都無關緊要。 但是為了輕松擴展測試數量,我將循環重構為以下形式:
for (const auto& pc : postcodeTests)
{
if (std::regex_match(toTest, pc.expression))
{
return pc.postcode;
}
}
在這種情況下, postcodeTests
可以是任何包含至少具有兩個成員的元素的集合: expression
和postcode
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.