Skip to content

Commit

Permalink
Added Encoder.globalUseJavaString option
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel committed Apr 15, 2024
1 parent 6baf72c commit 959f034
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,16 @@ fun interface Encoder<T> {

companion object {

var globalUseJavaString: Boolean = false

/**
* Returns an [Encoder] that encodes by simply returning the input value.
*/
fun <T : Any> identity(): Encoder<T> = Encoder { _, value -> value }

fun encoderFor(type: KType): Encoder<*> {
val encoder: Encoder<*> = when (val classifier = type.classifier) {
String::class -> StringEncoder
String::class -> if (globalUseJavaString) JavaStringEncoder else StringEncoder
Boolean::class -> BooleanEncoder
Float::class -> FloatEncoder
Double::class -> DoubleEncoder
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ object StringEncoder : Encoder<String> {
}
}

/**
* An [Encoder] for strings which always uses the JVM String object regardless
* of any [GenericData.STRING_PROP] settings on the schema.
*/
object JavaStringEncoder : Encoder<String> {
override fun encode(schema: Schema, value: String) = value
}

object UUIDEncoder : Encoder<UUID> {
override fun encode(schema: Schema, value: UUID): Any {
return Utf8(value.toString())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,37 @@ fun main() {

GenericData.setStringType(schema, GenericData.StringType.String)

// repeat(5) {
// val time = measureTime {
// repeat(5_000_000) {
// ReflectionRecordEncoder().encode(schema, user)
// }
// }
// println("ReflectionRecordEncoder: $time")
// }
repeat(2) {
val time = measureTime {
repeat(2_000_000) {
ReflectionRecordEncoder().encode(schema, user)
}
}
println("ReflectionRecordEncoder: $time")
}

repeat(10) {
val encoder = SpecificRecordEncoder(User::class, schema)
val time = measureTime {
repeat(2_000_000) {
encoder.encode(schema, user)
}
}
println("SpecificRecordEncoder globalUseJavaString=false: $time")
}

repeat(5) {
repeat(10) {
Encoder.globalUseJavaString = true
val encoder = SpecificRecordEncoder(User::class, schema)
val time = measureTime {
repeat(5_000_000) {
repeat(2_000_000) {
encoder.encode(schema, user)
}
}
println("SpecificRecordEncoder: $time")
println("SpecificRecordEncoder globalUseJavaString=true: $time")
}

repeat(5) {
repeat(10) {

val encoder = Encoder<User> { schema, value ->
val record = GenericData.Record(schema)
Expand All @@ -58,7 +69,7 @@ fun main() {
}

val time = measureTime {
repeat(5_000_000) {
repeat(2_000_000) {
encoder.encode(schema, user)
}
}
Expand Down

0 comments on commit 959f034

Please sign in to comment.