FlatBuffers aren’t fast, they’re lazy

Lots of great Android developers have been promoting FlatBuffers.

Miroslaw Stanek recently posted benchmarks comparing JSON, FlatBuffers, and a hybrid that uses both. He mentioned that decoding JSON to FlatBuffers is about 30-40% faster than decoding JSON to Java models with Gson.

Colt McAnlis has been referring Android developers to his video on FlatBuffers, where he explains some FlatBuffers implementation details:

“This layout allows FlatBuffers to be type safe and further allows you to read from the serialized type format without having to do any type conversions, memory allocations, or unpacking during load time which is a huge speed boost”

Note that FlatBuffers don’t do memory allocations during load time. Well, then when does the memory allocation happen?

FlatBuffers allocate every single time you access a non-primitive property of your object. Every. Single. Time. This is bad. It means allocation is likely happening in your onDraw() method, the dangers of this are well-explained by Ian Ni-Lewis in Avoiding Allocations in onDraw().

When you use FlatBuffers in an Android app, you’re moving work from the background I/O thread to the main thread. The best way to avoid this is by avoiding FlatBuffers.