While going through some code earlier today, I encountered a method that attempted to escape quotes and back slashes in a poor way. The author of that method presumably thought that it’d be way faster than Jackson’s ObjectMapper.
Here’s what they wrote:
This produced illegal JSON strings, especially when the input string had new lines and carriage returns in it.
Here’s what I replaced it with:
At first, I was uncertain about the efficiency of either approaches. Let’s JMH it:
The results were quite astounding. I hadn’t expected something like the following:
Benchmark Mode Cnt Score Error Units Benchmarks.jsonStringManual thrpt 2 83301.447 ops/s Benchmarks.jsonStringSerialization thrpt 2 4171309.830 ops/s
There must be something wrong, right? Perhaps it’s because of the static string. Let’s replace our static string with a random one generated for each iteration:
Here’s the JMH report:
Benchmark Mode Cnt Score Error Units Benchmarks.jsonStringManual thrpt 2 133432.951 ops/s Benchmarks.jsonStringSerialization thrpt 2 1535802.541 ops/s Benchmarks.randomString thrpt 2 2871443.990 ops/s
KISS. Premature optimisations are harmful. Not only can they introduce bugs, but they could be slower than the industry standard. Benchmark everything carefully.