rfc:json_preserve_fractional_part

This is an old revision of the document!


PHP RFC: JSON Preserve Fractional Part

Introduction

This RFC suggests adding a new option to json_encode function to keep the fractional part on float values.

Proposal

Currently encoding float values like 10.0 to json encodes it as 10, it means that using json_decode function it decodes as integer. The new flag allows the encode to keep the float number encoding 10.0 to 10.0 in JSON.

// Currently
var_dump(json_decode(json_encode((float)10))); // Output int(10)
 
// Proposed
var_dump(json_decode(json_encode((float)10, JSON_PRESERVE_FRACTIONAL_PART))); // Output double(10)

Backward Incompatible Changes

This RFC introduces no BC breaks.

Proposed PHP Version(s)

The next PHP 5.x.y.

RFC Impact

To SAPIs

No impact.

To Existing Extensions

No impact.

To Opcache

No impact.

New Constants

- JSON_PRESERVE_FRACTIONAL_PART: Preserve the fraction part of float numbers with zero as decimal part.

Performance

The implementation of this RFC changed how to encode float numbers and it affected the performance of the json_encode even when not using the new flag.

The table below shows the performance of the code below (PS: not using the new flag):

$data = array_fill(0, 1000, 1.1);
$iterations = 10000;
 
while ($iterations-- > 0) {
        json_encode($data);
}
+-------------------------------------------------------------------------------------+
| Number | With changes | Elapsed time                   | Peak Memory (real = false) |
+-------------------------------------------------------------------------------------+
| 1.0    | No           | 2.6276361942291                | 331 688                    |
| 1.0    | Yes          | 1.9471561908722 (25.9% faster) | 331 496                    |
| 1.1    | No           | 2.672217130661                 | 335 616                    |
| 1.1    | Yes          | 2.0137410163879 (24.6% faster) | 335 424                    |
+-------------------------------------------------------------------------------------+

PS: Tests executed from Mac OS X 10.10.1 using CPU 2.3 GHz Intel Core i7 and 16GB of RAM.

PS 2: The changes made on this RFC doesn't affect the performance of other value types.

Future Scope

Define if this behavior should be enabled by default in PHP 7.

Proposed Voting Choices

This RFC requires a 50%+1 majority.

Patches and Tests

Currently implemented on https://github.com/php/php-src/pull/642

Rejected Features

None so far.

rfc/json_preserve_fractional_part.1419531507.txt.gz · Last modified: 2017/09/22 13:28 (external edit)