flatBuffers is an efficient cross platform serialization library for C++, C#, C, Go, Java, Kotlin, JavaScript, Lobster, Lua, TypeScript, PHP, Python, Rust and Swift. It was originally created at Google for game development and other performance-critical applications.
In lua/luajit, is flatbuffers really faster than json?
I make a simple benchmark. Let’s see what’s the result.
mkdir /tmp/fb_bench
cd$_git clone https://github.com/google/flatbuffers flatbuffers.repo
cp -a flatbuffers.repo/lua/flatbuffers* .
apt install -y flatbuffers-compiler
flatc --lua test.fbs
luarocks install lua-cjson lua-protobuf
# serializationtime luajit -e "require('runfb').marshal_bench()"1584000000real 2m18.694s
user 2m14.777s
sys 0m0.446s
time luajit -e "require('runjson').marshal_bench()"1242000000real 0m13.712s
user 0m13.438s
sys 0m0.030s
time luajit -e "require('runpb').marshal_bench()"477000000real 0m29.054s
user 0m28.377s
sys 0m0.060s
# deserializationtime luajit -e "require('runfb').unmarshal_bench()"45000000real 1m59.111s
user 1m55.956s
sys 0m0.392s
time luajit -e "require('runjson').unmarshal_bench()"45000000real 0m28.408s
user 0m27.686s
sys 0m0.092s
time luajit -e "require('runpb').unmarshal_bench()"45000000real 0m28.245s
user 0m27.531s
sys 0m0.089s
Conclusion
You could see that json is faster than flatbuffers a lot, even the serialization size is better a bit.
And the protobuf is half of speed in serialization compared to JSON, but deserialization is almost the same.
Of course, it’s for lua only, and my test schema only contains string types.
You need to make a similar benchmark in your scenario.
I do not have time to investigate the reason, but I guess it’s due to the lua implementation of flatbuffers:
it handle each field of struct via lua code, including table iteration, but cjson handles everything in C land, as well as lua-protobuf.
JSON is my favourite format.
Besides performance, it has below advantages:
no schema
no code generation
human readable
If you’re worrying about the size of JSON for huge data, you could use lz4 to do compression, which has low CPU overhead.