dongyan8896 2010-01-12 14:02
浏览 46
已采纳

PHP打开包装问题

list(,$nfields) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;

The question is, why "N*" if substr should return 4 bytes, and they will be unpacked as N? And why double assignment?

UPD: This code is part of Sphinx native PHP connector. After some code hacking it became clear that this code extracts 4-byte integer. But logic behind double assignment and substr / N* is still unclear to me. I'm offering a bounty to finally understand it.

  • 写回答

3条回答 默认 最新

  • drpp5680 2010-01-14 18:00
    关注

    We'd need to see the revision history of the file but some possibilities are:

    1. These are the remains of a previous algorithm that was progressively stripped of functionality but never cleaned up.
    2. It's the typical spaghetti code we all produce after a bad night.
    3. It's an optimization that speeds up the code for large input strings.

    These are all synonyms:

    <?php
    
    $packed = pack('N*', 100, 200, 300);
    
    // 1
    var_dump( unpack('N*', $packed) );
    
    // 2
    var_dump( unpack('N*', substr($packed, 0, 4)) );
    var_dump( unpack('N*', substr($packed, 4, 4)) );
    var_dump( unpack('N*', substr($packed, 8, 4)) );
    
    // 3
    var_dump( unpack('N', substr($packed, 0, 4)) );
    var_dump( unpack('N', substr($packed, 4, 4)) );
    var_dump( unpack('N', substr($packed, 8, 4)) );
    
    ?>
    

    I did the typical repeat-a-thousand-times benchmark with three integers and 1 is way faster. However, a similar test with 10,000 integers shows that 1 is the slowest :-!

    0.82868695259094 seconds
    0.0046610832214355 seconds
    0.0029149055480957 seconds
    

    Being a full-text engine where performance is a must, I'd dare say it's an optimization.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?