Skip to content

Instantly share code, notes, and snippets.

@yarinb
Last active August 30, 2015 22:10
Show Gist options
  • Save yarinb/4c72c22894cefca0b223 to your computer and use it in GitHub Desktop.
Save yarinb/4c72c22894cefca0b223 to your computer and use it in GitHub Desktop.
Json4s with many custom formats
package com.indeni.measurements
import com.mongodb.DBObject
import com.mongodb.util.JSON
import org.json4s.ext.JodaTimeSerializers
import org.json4s.mongo.JObjectParser
import org.json4s.{DefaultFormats, Formats, JValue}
import org.scalatest._
case class SimpleObject(name: String, map: Map[String, Long], aNumber: Long)
class Json4sPerformanceSpec extends FlatSpec with ShouldMatchers with BeforeAndAfter {
val TOTAL_RUNS = 100000
val jsonString =
"""{'name': 'This is the obj name',
| 'map': {
| 'key1': 91236817623,
| 'key2': 91236817623,
| 'key3': 91236817623
| },
| 'aNumber': 71253716253
| }""".stripMargin
class MovingAverage(period: Int) {
private val queue = new scala.collection.mutable.Queue[Double]()
def update(n: Double) = {
queue.enqueue(n)
if (queue.size > period)
queue.dequeue()
queue.sum / queue.size
}
override def toString = s"${queue.mkString("(", ", ", ")")} , period $period, average ${queue.sum / queue.size}"
def average = s"average ${queue.sum / queue.size}"
def clear = queue.clear()
}
def measure[R](block: => R): Long = {
val start = System.nanoTime()
val result = block
val end = System.nanoTime()
end - start
}
it should s"run a $TOTAL_RUNS ser-deser of SimpleObject with DefaultFormats" in {
implicit val formats: Formats = DefaultFormats
val dbObject = JSON.parse(jsonString).asInstanceOf[DBObject]
val movingAverage = new MovingAverage(1000)
for (i <- 1 to TOTAL_RUNS) {
val elapsed = measure {
val jval: JValue = JObjectParser.serialize(dbObject)
val m: SimpleObject = jval.extract[SimpleObject]
assert(m.aNumber == 71253716253L)
}
movingAverage.update(elapsed)
}
println(movingAverage.average)
}
it should s"run a $TOTAL_RUNS ser-deser of SimpleObject with CustomFormats" in {
implicit val formats: Formats = DefaultFormats ++ JodaTimeSerializers.all
val dbObject = JSON.parse(jsonString).asInstanceOf[DBObject]
val movingAverage = new MovingAverage(1000)
for (i <- 1 to TOTAL_RUNS) {
val elapsed = measure {
val jval: JValue = JObjectParser.serialize(dbObject)
val m: SimpleObject = jval.extract[SimpleObject]
assert(m.aNumber == 71253716253L)
}
movingAverage.update(elapsed)
}
println(movingAverage.average)
}
}
@yarinb
Copy link
Author

yarinb commented Aug 30, 2015

Spec output:

Testing started at 11:59 PM ...
Elapsed time: 15391ms
Elapsed time: 2568ms

Process finished with exit code 0

@yarinb
Copy link
Author

yarinb commented Aug 30, 2015

@talgendler Thought you wanna be aware of this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment