serialize a large array in PHP?

前端 未结 13 2040
死守一世寂寞
死守一世寂寞 2021-01-04 06:11

I am curious, is there a size limit on serialize in PHP. Would it be possible to serialize an array with 5,000 keys and values so it can be stored into a cache?

I am

13条回答
  •  庸人自扰
    2021-01-04 06:33

    Ok... more numbers! (PHP 5.3.0 OSX, no opcode cache)

    @Pascal's code on my machine for n=1 at 10k iters produces:

    float(18.884856939316)
    int(1075900)
    

    I add unserialize() to the above as so.

    $num = 1;
    
    $list = array_fill(0, 5000, str_repeat('1234567890', $num));
    
    $before = microtime(true);
    for ($i=0 ; $i<10000 ; $i++) {
        $str = serialize($list);
        $list = unserialize($str);
    }
    $after = microtime(true);
    
    var_dump($after-$before);
    var_dump(memory_get_peak_usage());
    

    produces

    float(50.204112052917)
    int(1606768) 
    

    I assume the extra 600k or so are the serialized string.

    I was curious about var_export and its include/eval partner $str = var_export($list, true); instead of serialize() in the original produces

    float(57.064643859863)
    int(1066440)
    

    so just a little less memory (at least for this simple example) but way more time already.

    adding in eval('$list = '.$str.';'); instead of unserialize in the above produces

    float(126.62566018105)
    int(2944144)
    

    Indicating theres probably a memory leak somewhere when doing eval :-/.

    So again, these aren't great benchmarks (I really should isolate the eval/unserialize by putting the string in a local var or something, but I'm being lazy) but they show the associated trends. var_export seems slow.

提交回复
热议问题