2013. 10. 28.

PHP mysql mysqli 데이터베이스 mysqli_fetch_row() mysqli_fetch_assoc() mysqli_fetch_array() 함수 차이.

PHP에서 데이터베이스 쿼리 함수들의 성능에 대한 글을 어쩌다가 봤다.
데이터베이스에서 결과 가져올때 흔히들 쓰는 함수들이다.
정확히 알지도 못하고, 소스에 사용된 부분이 있으면 긁어서 쓰고 또 썼었다.
맨날 긁어서 쓰기만 하니까 기억이 안나서 검색을 좀 해봤다.

array mysql_fetch_row ( resource $result )
array mysql_fetch_assoc ( resource $result )
array mysql_fetch_array ( resource $result [,int $result_type = MYSQL_BOTH ] )

mixed mysqli_fetch_row ( mysqli_result $result )
array mysqli_fetch_assoc ( mysqli_result $result )
mixed mysqli_fetch_array ( mysqli_result $result [,int $resulttype = MYSQLI_BOTH ] )

일단 mysqli_fetch_row().
값을 꺼내오는데 [index] 숫자값을 사용한다.

$connection = new mysqli("localhost", "id", "pw", "database");
$query = " SQL QUERY ";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_row($result);
$row[0], $row[1] ...

그리고 mysqli_fetch_assoc().
필드명이나 쿼리문에 사용된 alias로 배열을 참조 할 수 있다.

...
$row = mysqli_fetch_assoc($result);
$row["Name"], $row["CountryCode"] ...

그럼 mysqli_fetch_array() 이녀석을 보자.

/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

이녀석은 위에서 본 두가지 배열을 다 만들어서 내놓는다. 두번째 파라미터 기본값으로 MYSQLI_BOTH가 들어간다. 달리 명시해 주지 않으면 두 가지 배열 다 만들어서 돌려 준다.
결국 mysqli_fetch_row() 함수와 mysqli_fetch_assoc() 함수를 동시에 쓰는 거다.
가져오는 데이터베이스 양이 적으면 3가지 중에 뭘 쓰든 별 상관 없다. 편한거 쓰면 된다.

천만개 정도 들어있는 데이터베이스에 쿼리를 날리면 어떻게 될까.
http://www.spearheadsoftwares.com/tutorials/php-performance-benchmarking/50-mysql-fetch-assoc-vs-mysql-fetch-array-vs-mysql-fetch-object

링크를 타고가서 확인해보면 백만개 정도부터 살짝 차이가 나기 시작한다.
mysqli_fetch_object()는 쿼리 결과를 객체로 만들어서 뱉어주는거라 생각 하면 된다.

$obj = mysqli_fetch_object($result);
$obj->Name, $obj->CountryCode) ...

객체로 만들어서 뱉어 주는거라, 그냥 왠지 느릴 것만 같은데 정말 늦다.
물론 이것도 데이터 양이 몇개 안되면 차이 없다.

천만개 정도 데이터 양이 있을때, object()와 assoc()의 성능을 비교해 보면 15초 이상 차이난다.
array()와 assoc()에서는 큰 차이를 보이진 않는다. 4초 정도 되려나. object()와 assoc()에서 15초 이상 차이가 나서 1초가 아주 작아 보인다. 0.1초라도 줄이기 위해 노력 하는데 ... 4초도 정말 큰 시간이다.

스택오버플로우 같은 곳들을 뒤지다 보니 mysqli_fetch_array() 함수를 잊으라고 추천한다.
row()와 assoc()은 따로 비교되지 않았다. row()가 만들어놓은 배열 index와 필드명을 이어 주는게 필요해 보이는데... 성능 차이가 거의 없는걸까. 아무래도 row()가 가장 빠를 것 같다.
아무튼,  mysqli_fetch_row() 또는 mysqli_fetch_assoc()을 사용하자.

* mysql_*() 함수들은 PHP 5.5.0 버전에서 부터 DEPRECATED 되었고, 미래에 함수 자체가 지워질 것이라 한다. 확장격인 mysqliPDO_MySQL을 사용하자.

관련 출처.
http://us2.php.net/mysql_fetch_assoc
http://www.php.net/manual/en/mysqli-result.fetch-assoc.php
http://www.php.net/manual/en/mysqli-result.fetch-array.php
http://stackoverflow.com/questions/11480129/mysql-fetch-row-vs-mysql-fetch-assoc-vs-mysql-fetch-array

댓글 1개 :