diff --git a/core/src/main/scala/sttp/model/MediaType.scala b/core/src/main/scala/sttp/model/MediaType.scala index b065a129..05c9695c 100644 --- a/core/src/main/scala/sttp/model/MediaType.scala +++ b/core/src/main/scala/sttp/model/MediaType.scala @@ -63,7 +63,9 @@ case class MediaType( def isModel: Boolean = mainType.equalsIgnoreCase("model") - override lazy val toString: String = { + // Cache 'toString' given that it's called in the hot path + // of request processing to generate headers. + private lazy val toStringCache: String = { val sb = new java.lang.StringBuilder(32) // "application/json; charset=utf-8".length == 31 ;) sb.append(mainType).append('/').append(subType) charset match { @@ -77,6 +79,7 @@ case class MediaType( sb.toString } + override def toString() = toStringCache override lazy val hashCode: Int = toString.toLowerCase.hashCode override def equals(that: Any): Boolean = diff --git a/core/src/test/scala/sttp/model/MediaTypeTests.scala b/core/src/test/scala/sttp/model/MediaTypeTests.scala index df7dfdd0..99d94e22 100644 --- a/core/src/test/scala/sttp/model/MediaTypeTests.scala +++ b/core/src/test/scala/sttp/model/MediaTypeTests.scala @@ -59,6 +59,12 @@ class MediaTypeTests extends AnyFlatSpec with Matchers with TableDrivenPropertyC an[IllegalArgumentException] shouldBe thrownBy(MediaType.unsafeApply("te=xt", "plain")) } + it should "have a regular toString" in { + val mt = MediaType.ApplicationGzip + mt.toString shouldBe "application/gzip" + mt.toString() shouldBe "application/gzip" + } + private val matchCases = Table( ("media type", "content type range", "matches"), // simple matching