天天看點

msgpack和json在php和js下的對比

最近在用cocos create +php做遊戲。聽說msgpack比json更快更小,我就做了下測試,結果如下:

msgpack官網:https://msgpack.org/

PHP

php的擴充使用PECL安裝

php代碼:

<?php
$arr=[
    'user'=>'xxxxx',
    'age'=>25,
    'sub'=>[
        'email'=>'sfsdfsdfd',
        'ad'=>'afsfsfsfds'
    ]
];
$str_pack=msgpack_pack($arr);
$json_str=json_encode($arr);
echo $str_pack,"\n",$json_str,"\n";

echo "msgpack:\n";
$time=microtime(true);

for($i=0;$i<1000000;$i++){
    msgpack_pack($arr);
}
$time2=microtime(true);
echo $time2-$time,"\n";

$time=microtime(true);
for($i=0;$i<1000000;$i++){
    msgpack_unpack($str_pack);
}
$time2=microtime(true);
echo $time2-$time,"\n\n";

echo "json:\n";
$time=microtime(true);
for($i=0;$i<1000000;$i++){
    json_encode($arr);
}
$time2=microtime(true);
echo $time2-$time,"\n";

$time=microtime(true);
for($i=0;$i<1000000;$i++){
    json_decode($json_str);
}
$time2=microtime(true);
echo $time2-$time,"\n";
           

測試結果:

¤user¥xxxxx£age£sub¥email©sfsdfsdfd¢adªafsfsfsfds
{"user":"xxxxx","age":25,"sub":{"email":"sfsdfsdfd","ad":"afsfsfsfds"}}
msgpack:
0.26375007629395
0.38215303421021

json:
0.17352199554443
0.78090310096741
           

如果無誤的話(若有誤請指正)可得出結論:pack的資料長度比json短,在PHP下json序列化的時間比msgpack要快,反序化json比msgpack要慢。

JS

js代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script src="magpack.js"></script>
<script>
    var obj={
        name:'sss',
        action:'sss',
        age:25,
        sub:{
            user:'sdfsdfsd',
            email:'sdfsdwrr3'
        }

    };
    console.log(obj);
    var json=JSON.stringify(obj);
    console.log(json);
    console.log(json.length);
    var pack_msg=msgpack.pack(obj);
    console.log(pack_msg);
    console.log(pack_msg.length);


    var time=new Date().getTime();
    for($i=0;$i<1000000;$i++){
        JSON.stringify(obj);
    }
    var time2=new Date().getTime();
    console.log("JSON 序列化:",time2-time);

    time=new Date().getTime();
    for($i=0;$i<1000000;$i++){
        JSON.parse(json);
    }
    time2=new Date().getTime();
    console.log("JSON 反序列化:",time2-time);

    //msgpack
    time=new Date().getTime();
    for($i=0;$i<1000000;$i++){
        msgpack.pack(obj);
    }
    time2=new Date().getTime();
    console.log("msgpack序列化:",time2-time);

    time=new Date().getTime();
    for($i=0;$i<1000000;$i++){
        msgpack.unpack(pack_msg);
    }
    time2=new Date().getTime();
    console.log("msgpack反序列化:",time2-time);
</script>
</html>
           

測試結果:

msgpack和json在php和js下的對比

從上圖結果可以看出(firefox浏覽器):在javascript下序列化json和msgpack相差不大,反序列化json比msgpack要快很多,msgpack資料長度比json要短。