intval과 int-`(int) X`로 캐스팅하는 데 특별한 차이점이 있습니까?
intval과 (int) 사이에 특별한 차이점이 있습니까?
예:
$product_id = intval($_GET['pid']);
$product_id = (int) $_GET['pid'];
위 두 줄의 코드 사이에 특별한 차이점이 있습니까?
intval()
변환 할 기준 을 전달할 수 있습니다 . (int)
할 수 없습니다.
int intval( mixed $var [, int $base = 10 ] )
의 차이에 대한주의 사항 한 가지 (int)
와 intval()
: intval()
취급 이미 변수 int
s와 float
(적어도 PHP 5.3.5 기준)에 관계없이 기본 인수, 어떤 변환을 필요로하지 않기 때문에이야. PHP 문서 페이지 의 주석에서 언급하고 여기에 뻔뻔스럽게 반복 된 것처럼이 동작은 가장 분명하지 않습니다 .
$test_int = 12;
$test_string = "12";
$test_float = 12.8;
echo (int) $test_int; // 12
echo (int) $test_string; // 12
echo (int) $test_float; // 12
echo intval($test_int, 8); // 12 <-- WOAH!
echo intval($test_string, 8); // 10
echo intval($test_float, 8) // 12 <-- HUH?
괴로워서 미안합니다. PHP7 이이 질문에 어떤 영향을 미치는지 확인하고 싶었습니다.
$ php -v
PHP 7.0.4-5+deb.sury.org~trusty+1 (cli) ( NTS )
시험:
php > $start_ts = microtime(true); for($i = 0; $i < 100000000; $i++) { $a = (int) '1'; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "3279.1121006012 ms"
php > $start_ts = microtime(true); for($i = 0; $i < 100000000; $i++) { $a = intval('1'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "5379.3351650238 ms"
보다시피, 캐스팅은 거의 100 % 빠릅니다.
그러나 차이가 몇 초가되기 전에 루프 카운트를 1 억으로 늘려야했는데, 실제로 대부분의 경우 성능에 관심을 갖기 시작했습니다.
intval
캐스팅은 약간의 언어 마술이기 때문에 함수 사용을 고수하겠습니다 . intval
배후에서 캐스팅을 사용 하더라도 캐스팅과 관련된 버그가 발견되고 어떤 이유로 든 수정할 수없는 경우 (이전 버전과의 호환성?) 최소한 intval
의무를 수행하도록 수정할 수 있습니다.
업데이트 (PHP 7.1 + 추가 사례) :
$ php -v
PHP 7.1.0RC6 (cli) (built: Nov 9 2016 04:45:59) ( NTS )
$ php -a
php > $start_ts = microtime(true); for($i = 0; $i < 100000000; $i++) { $a = (int) '1'; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "3583.9052200317 ms"
php > $start_ts = microtime(true); for($i = 0; $i < 100000000; $i++) { $a = intval('1'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "3569.0960884094 ms"
php > $start_ts = microtime(true); for($i = 0; $i < 100000000; $i++) { $a = '1' + 0; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "1641.7920589447 ms"
7.1 최적화 된 것처럼 보이며 intval
'1'+ 0 이이 스피드 콘테스트의 승자가되었습니다.) intval
어쨌든 계속 사용 하고 있습니다.
I think there is at least one difference : with intval, you can specify which base should be used as a second parameter (base 10 by default) :
var_dump((int)"0123", intval("0123"), intval("0123", 8));
will get you :
int 123
int 123
int 83
Amber is right and if I may add a useful information type casting (adding a "(int)" before your expression ) is 300 to 600% faster than intval. So if your purpose is not to dealing with other bases than decimal, I recommend using: (int) $something
One useful property of intval
is that - since it is a function and not a language construct - it can be passed as an argument to a function that expects a function. You can't do this with (int)
.
For example, I have used it to sanitize integers for inclusion into a SQL IN()
clause by passing it to array_map
. Here is an example:
$ids = implode(",", array_map('intval', $_POST['array_of_integers']));
$sql = "SELECT * FROM table WHERE ids IN ($ids)";
The thing that intval
does that a simple cast doesn't is base conversion:
int intval ( mixed $var [, int $base = 10 ] )
If the base is 10 though, intval
should be the same as a cast (unless you're going to be nitpicky and mention that one makes a function call while the other doesn't). As noted on the man page:
The common rules of integer casting apply.
'Programing' 카테고리의 다른 글
5 살짜리에게 의존성 주입을 설명하는 방법? (0) | 2020.05.01 |
---|---|
Windows를위한 좋은 Valgrind 대체품이 있습니까? (0) | 2020.04.30 |
왜 파이썬에는 부호 함수가 없습니까? (0) | 2020.04.30 |
동적 변수에서 속성을 사용할 수 있는지 테스트 (0) | 2020.04.30 |
쿼리 문자열 매개 변수 및 숨겨진 매개 변수가 포함 된 GET 양식을 제출하면 사라집니다. (0) | 2020.04.30 |