最近在用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>
测试结果:

从上图结果可以看出(firefox浏览器):在javascript下序列化json和msgpack相差不大,反序列化json比msgpack要快很多,msgpack数据长度比json要短。