google / gson

A Java serialization/deserialization library to convert Java Objects into JSON and back
Apache License 2.0
23.13k stars 4.27k forks source link

Improved Long-Double Number Policy #2674

Closed ctasada closed 1 month ago

ctasada commented 2 months ago

Purpose

Fixes a performance issue while using the ToNumberPolicy.LONG_OR_DOUBLE with Double values

Description

The Parsing of a Double value was always executing a Long.parseLong(value), which generated a NumberFormatException.

Identifying that a Number is a Double or a Long can be easily achieve (in a naive way) looking for the decimal separator.

This simple change avoids the extra NumberFormatException

A simple JUnit test, parsing a Long or a Double 10K times shows the next values:

As we can see, the parsing for Long values stays the same (±1ms), while the parsing for Double is dramatically improved.

Reducing the number of exceptions also has a positive side effect in memory consumption.

Checklist

google-cla[bot] commented 2 months ago

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.