mysqli_fetch_array() or mysqli_fetch_all()?

后端 未结 2 876
花落未央
花落未央 2021-01-19 10:59

I see comparisons between mysqli_fetch_array() and mysqli_fetch_all() that say that with mysqli_fetch_all() it will take more memory a

相关标签:
2条回答
  • 2021-01-19 11:34

    From PHP's page on mysql_fetch_all():

    I tested using fetch_all versus while / fetch_array and:

    fetch_all uses less memory (but not for so much).

    In my case (test1 and test2): 147008,262848 bytes (fetch_all) versus 147112,262888 bytes (fetch_array & while).

    So, about the memory, in both cases are the same.

    However, about the performance:

    My test takes :350ms (worst case) using fetch_all, while it takes 464ms (worst case) using fetch_array, or about 35% worst using fetch_array and a while cycle.

    So, using fetch_all, for a normal code that returns a moderate amount of information is:

    a. cleaner (a single line of code)
    b. uses less memory (about 0.01% less)
    c. faster.

    php 5.6 32bits, windows 8.1 64bits

    0 讨论(0)
  • 2021-01-19 11:40

    It has nothing to do with whatever efficiency. It's all about usability only.

    fetch_all() is a thing that is called a "syntax sugar" - a shorthand to automate a frequently performed operation. It can be easily implemented as a userland function:

    function mysqli_fetch_all ($resouce, $mode = MYSQLI_BOTH)
    {
        $ret = [];
        while ($row = $resource->fetch_array($mode))
        {
            $ret[] = $row;
        }
        return $ret;
    }
    

    Thus you can tell use cases for these functions:

    • fetch_all() have to be used if you need an array, consists of all the returned rows, that will be used elsewhere.
    • fetch_assoc() in a loop have to be used if you're going to process all the rows one by one right in place.

    As simple as that.

    These functions bear different purpose and thus there is no point in comparing them.

    Note that PDO is tenfold more sweet in terms of syntax sugar, as it's fetchAll() function can return data in dozens different formats

    0 讨论(0)
提交回复
热议问题