In PHP, is there any harm in running session_start() multiple times?

前端 未结 7 864
臣服心动
臣服心动 2020-12-03 13:37

Presumably there\'s some tiny performance hit, but beyond that?

7条回答
  •  鱼传尺愫
    2020-12-03 13:58

    Calling session_start(); can harm the performance of your application.

    The following code will trigger an E_NOTICE, but won't harm that much performance wise

    
    

    But calling the following will harm the performance! But it's still useful. If you have a script that takes like 3 minutes to run and is called with XHR (js). In this case it's useful to use the session_write_close. otherwise the request to the server is blocked until the sessions are released. It could happen that you want to use the sessions at the start of the script and at the end of the script.

    
    

    But, when you call the session_start(); all information is deserialized, and when you call session_write_closed() it's serialized. So if you have a lot of data it can be really slow!

    The following test shows how much impact it has.

    1.0130980014801 sesion_start + close with empty session

    1.0028710365295 normal loop without session

    12.808688879013 a lot data in the session with start + close

    1.0081849098206 normal loop again (useless kinda)

    ');
        $start = microtime(true);
        for($i = 0; $i < 1000; $i++) {
            usleep(100);
        }
        $end = microtime(true);
        echo($end - $start);
    }
    
    
    //fill the array with information so serialization is needed
    session_start();
    $_SESSION['test'] = array();
    for($i = 0; $i < 10000; $i++) {
        $_SESSION['test'][$i] = chr($i);
    }
    session_write_close();
    echo('
    '); //test two if(true) { //test loop one $start = microtime(true); for($i = 0; $i < 1000; $i++) { session_start(); usleep(100); session_write_close(); } $end = microtime(true); echo($end - $start); //test loop 2 echo('
    '); $start = microtime(true); for($i = 0; $i < 1000; $i++) { usleep(100); } $end = microtime(true); echo($end - $start); } ?>

提交回复
热议问题