Skip to content

Commit 3b4dbe6

Browse files
committed
Reduce allocations when writing Float, Double, and Long values by uPickle
1 parent 49726d5 commit 3b4dbe6

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

jsoniter-scala-benchmark/shared/src/main/scala/com/github/plokhotnyuk/jsoniter_scala/benchmark/UPickleReaderWriters.scala

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,21 @@ object UPickleReaderWriters extends AttributeTagged {
1313
implicit val bigDecimalWriter: Writer[BigDecimal] = numWriter[BigDecimal]
1414
implicit val bigIntReader: Reader[BigInt] = numReader(s => BigInt(s.toString))
1515
implicit val bigIntWriter: Writer[BigInt] = numWriter[BigInt]
16-
implicit val doubleWriter: Writer[Double] = numWriter[Double]
17-
implicit val floatWriter: Writer[Float] = numWriter[Float]
18-
implicit val longWriter: Writer[Long] = numWriter[Long]
16+
implicit val doubleWriter: Writer[Double] = new Writer[Double] {
17+
def write0[R](out: Visitor[_, R], v: Double): R =
18+
if (v.toLong.toDouble != v) out.visitFloat64(v, -1)
19+
else out.visitFloat64String(v.toString, -1)
20+
}
21+
implicit val floatWriter: Writer[Float] = new Writer[Float] {
22+
def write0[R](out: Visitor[_, R], v: Float): R =
23+
if (v.toInt.toFloat != v) out.visitFloat32(v, -1)
24+
else out.visitFloat64String(v.toString, -1)
25+
}
26+
implicit val longWriter: Writer[Long] = new Writer[Long] {
27+
def write0[R](out: Visitor[_, R], v: Long): R =
28+
if (v > -4503599627370496L && v < 4503599627370496L) out.visitInt64(v, -1)
29+
else out.visitFloat64String(v.toString, -1)
30+
}
1931
@annotation.nowarn implicit lazy val adtReadWriter: ReadWriter[ADTBase] =
2032
ReadWriter.merge(tagName, macroRW[X], macroRW[Y], macroRW[Z])
2133
implicit val anyValsReadWriter: ReadWriter[AnyVals] = {

0 commit comments

Comments
 (0)