簡體   English   中英

Filter_var的表現

[英]Filter_var's performance

我讀到filter_var不在內部使用regexp。 這是否意味着它比preg_match快得多?

我想檢查電子郵件驗證是否考慮了速度性能。

編輯

這不是重復的:我不是在問區別(關於filter_var和preg_match的優點是什么),但是執行起來更快(有或沒有緩存)。 此外,在注釋中,它表明filter_var像preg_match一樣使用regexp,並且此信息在相關問題中被完全忽略。

從快速基准測試來看,似乎filter_var()函數的速度快一些:

$times = 10000;

$result = array();

// preg_match version
// regex from https://github.com/php/php-src/blob/master/ext/filter/logical_filters.c#L525
$regexp = "/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD";

$email = 'foo@bar.com';

$start_m = microtime();
$start = time();
for ($i=0; $i < $times; $i++){
      preg_match($regexp, $email);
}   

$end_m = microtime();
$end = time();
$bench = ($end - $start) + ($end_m - $start_m);
$result["preg_match"] = $bench;


// filter_var version
$start_m = microtime();
$start = time();
for ($i=0; $i < $times; $i++){
      filter_var($email, FILTER_VALIDATE_EMAIL);
}

$end_m = microtime();
$end = time();
$bench = ($end - $start) + ($end_m - $start_m);
$result["filter_var"] = $bench;

print_r(
    array(
      "times" => $times,
      "results" => $result
    )
);

(對本要點進行略微修改的代碼)

結果在我的系統上:

PHP 5.5.9-1+sury.org~saucy+1 (cli) (built: Feb 13 2014 16:01:20) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies

Array
(
    [times] => 10000
    [results] => Array
        (
            [preg_match] => 0.16649
            [filter_var] => 0.110912
        )

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM