Skip to content

Commit

Permalink
Significant performance optimization to the serializiation of decimal…
Browse files Browse the repository at this point in the history
…s - trailing zeroes are now truncated after the serialization, avoiding the expensive division by 1.00000000000000000.
  • Loading branch information
zlatanov committed Feb 8, 2019
1 parent 2ca56ef commit bea4458
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions src/JsonWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -380,17 +380,36 @@ public void WriteValue( Decimal value )
{
WriteStarted( State.Value );

// Do not serialize trailing zeroes. The current version of the Utf8Formatter we use
// do not allow us to specify that we don't want any.
// https://stackoverflow.com/a/7983330/132690
value /= 1.0000000000000000000000000000M;
var span = m_output.GetSpan( Constants.MaxDecimalSize );

if ( !Utf8Formatter.TryFormat( value, m_output.GetSpan(), out var bytesWritten ) &&
!Utf8Formatter.TryFormat( value, m_output.GetSpan( Constants.MaxDecimalSize ), out bytesWritten ) )
if ( !Utf8Formatter.TryFormat( value, span, out var bytesWritten ) )
{
ThrowFormatException( value );
}

// Do not serialize trailing zeroes. The current version of the Utf8Formatter we use
// do not allow us to specify that we don't want any.
if ( span[ bytesWritten - 1 ] == (Byte)'0' )
{
// Find out if the decimal has a decimal point
var pointIndex = span.LastIndexOf( (Byte)'.' );

if ( pointIndex != -1 )
{
--bytesWritten;

while ( span[ bytesWritten - 1 ] == (Byte)'0' )
{
--bytesWritten;
}

if ( bytesWritten - 1 == pointIndex )
{
--bytesWritten;
}
}
}

m_output.Advance( bytesWritten );
}

Expand Down

0 comments on commit bea4458

Please sign in to comment.