Optimizing type checks/casts for json building Optimizing type checks/casts for json building json json

Optimizing type checks/casts for json building


TL;DR It's fine as it is.


Concerning optimization, note that you're adding everything to a builder, which (I guess) build, while you probably want a String or even a byte[] to be sent over the wire.

Recently, I read somewhere that Gson typically spends much more time copying string than doing reflection. So I wouldn't care much.

What's bugging me is that it does not support adding/writing of Object.

If they would, then they'd have to provide either an incomplete solution like you do (which is fine for you, but not for a library) or make it extensible, and then there's Jackson, Gson and many others already.

I am wondering, if there is any way to optimize this code.

I can think of two ways and recommend neither:

1: Find some groupings, so that the number of cases gets smaller. You could test value instanceof Number and then branch further. However, there'd be hardly any gain, as numbers are surely much more common than the remaining cases.

2: Create a Map<Class, Consumer<Object>> populated with converters for you cases and use something like

map.get(value.getClass()).accept(value);

This could be a good solution when the number of cases is huge or when you need extensibility. For your 10 cases, it'd most probably lead to a substantial slowdown.

The other part is that I want to pass JsonObjectBuilder or JsonGenerator for consumer in order to cut some duplicated checks/code.

I don't think, it'll be worth it. JsonObjectBuilder and JsonGenerator are two unrelated interfaces. Both of them have a bunch of methods, which are related, yet differently named and not always corresponding with each other. So you'd need to write wrappers for both of them or duplicate code like in your question. Finally, you get some duplicated code, anyway.

And it'll be rather ugly. I'd suggest to have a look at more powerful tools like Gson or Jackson or whatever.