0

I'm building a Kotlin server application. I know that I will need a specific Json configuration such as Json { ignoreUnknownKeys = true } throughout.

My question is whether it makes more sense to declare a top-level var (or maybe an object with the config as a property) and use that everywhere, or whether to create a new Json {} within each function.

I guess my concern with using a singleton is a tie-up in the case when I have multiple simultaneous requests coming in all of which need to use the config. I don't know enough about JVM internals or the kotlinx architecture to know if that is an issue. Meanwhile, creating a new config within every function seems highly inefficient, creating new objects every time.

// which to choose?

// top-level val
val myJson : Json = Json { ignoreUnknownKeys = true }

// top-level object with property
object myJConfig {
  val myJson : Json = { ignoreUnknownKeys = true }
}

// create a new config within a function
class myClass {
  fun myFunc() {
    val myJson : Json = { ignoreUnknownKeys = true }
    ... rest of function here ...
  }
}
ExactaBox
  • 3,235
  • 16
  • 27
  • 1
    There is no issues with multiple users of a certain "thing". The issue is with concurrent modification, so as long as none of your procedures actually change something in your object, a singleton will be fine. – AlexT Jan 27 '21 at 10:10
  • @Alex.T thanks. no there will not be any modification. I was concerned about a slowdown if one request is currently using the parser, another request would have to wait until the first one is done. If parsing a long JSON string takes, say 250ms, am I limiting my server from handling any more than 4 requests per second? – ExactaBox Jan 27 '21 at 20:52

1 Answers1

0

Instance of Json is tread-safe (so are all KSerializers). It's instance of Encoder or Decoder that is context-specific for object you encode/decode.

expert
  • 29,290
  • 30
  • 110
  • 214