From 2dbd94951c6c77a27a6c9c50ebb393c0ac550d32 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Sun, 10 Jul 2016 16:12:49 +0200 Subject: [PATCH] Improved speed of float serialization (about twice faster) --- CHANGELOG.md | 5 +++++ include/ArduinoJson/Internals/JsonWriter.hpp | 18 +++++++++--------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9966083..4ca44885 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ ArduinoJson: change log ======================= +HEAD +---- + +* Improved speed of float serialization (about twice faster) + v5.6.2 ------ diff --git a/include/ArduinoJson/Internals/JsonWriter.hpp b/include/ArduinoJson/Internals/JsonWriter.hpp index 5df2e68f..c7f26b26 100644 --- a/include/ArduinoJson/Internals/JsonWriter.hpp +++ b/include/ArduinoJson/Internals/JsonWriter.hpp @@ -98,12 +98,6 @@ class JsonWriter { powersOf10 = 0; } - // Round correctly so that print(1.999, 2) prints as "2.00" - JsonFloat rounding = 0.5; - for (uint8_t i = 0; i < digits; ++i) rounding /= 10.0; - - value += rounding; - // Extract the integer part of the value and print it JsonUInt int_part = static_cast(value); JsonFloat remainder = value - static_cast(int_part); @@ -116,10 +110,16 @@ class JsonWriter { // Extract digits from the remainder one at a time while (digits-- > 0) { + // Extract digit remainder *= 10.0; - JsonUInt toPrint = JsonUInt(remainder); - writeInteger(JsonUInt(remainder)); - remainder -= static_cast(toPrint); + char currentDigit = char(remainder); + remainder -= static_cast(currentDigit); + + // Round up last digit (so that print(1.999, 2) prints as "2.00") + if (digits == 0 && remainder >= 0.5) currentDigit++; + + // Print + writeRaw(char('0' + currentDigit)); } if (powersOf10 < 0) {