### Build and Measure JVM Startup Time Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Builds an uber JAR for the example, prints its size, and measures its startup time using 'perf stat'. Requires specific Linux tools and Oracle GraalVM. ```sh sudo apt install linux-tools-common linux-tools-generic sudo sysctl kernel.perf_event_paranoid=1 scala-cli --power package --assembly example01.sc --force -o example01.jar ls -l ./example01.jar perf stat -r 100 java --sun-misc-unsafe-memory-access=allow -jar ./example01.jar > /dev/null ``` ```text Performance counter stats for './example01.jar' (100 runs): 205.66 msec task-clock # 2.215 CPUs utilized ( +- 0.30% ) 1,624 context-switches # 7.897 K/sec ( +- 0.83% ) 17 cpu-migrations # 82.662 /sec ( +- 1.67% ) 23,158 page-faults # 112.605 K/sec ( +- 0.09% ) 1,195,984,140 cpu_atom/instructions/ # 1.57 insn per cycle ( +- 1.24% ) 906,422,673 cpu_core/instructions/ # 1.77 insn per cycle ( +- 2.94% ) (39.78%) 762,329,450 cpu_atom/cycles/ # 3.707 GHz ( +- 1.34% ) 513,382,841 cpu_core/cycles/ # 2.496 GHz ( +- 3.75% ) (39.78%) 237,678,684 cpu_atom/branches/ # 1.156 G/sec ( +- 1.24% ) 174,316,667 cpu_core/branches/ # 847.610 M/sec ( +- 3.18% ) (39.78%) 6,725,338 cpu_atom/branch-misses/ # 2.83% of all branches ( +- 1.78% ) 5,919,295 cpu_core/branch-misses/ # 3.40% of all branches ( +- 4.63% ) (39.78%) 0.092830 +- 0.000511 seconds time elapsed ( +- 0.55% ) ``` -------------------------------- ### Install Prerequisites for Scala.js and Scala Native Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Install Clang 18.x and Node.js 16.x, which are prerequisites for building Scala.js and Scala Native modules. This sequence includes apt installation, nvm setup, and Node.js version management. ```sh sudo apt install clang libstdc++-12-dev libgc-dev curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash source ~/.bashrc nvm install 16 node -v ``` -------------------------------- ### Run parametrized JVM benchmarks Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Set constant values for benchmark parameters using the `-p` option. This example sets the `size` parameter to multiple values. ```sh sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -p size=1,10,100,1000 ArrayOf.*' ``` -------------------------------- ### Build GraalVM Native Image, Measure Startup Time Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Builds Scala code into a GraalVM native image, then measures its startup time using `perf`. Requires specific system packages and GraalVM setup. ```sh sudo apt install linux-tools-common linux-tools-generic gcc zlib1g-dev sudo sysctl kernel.perf_event_paranoid=1 scala-cli --power package --graalvm-jvm-id graalvm-oracle:24 --native-image example01.sc --force -o example01_graalvm.bin -- --no-fallback -O3 -H:+UnlockExperimentalVMOptions -R:MaxHeapSize=16m -H:-GenLoopSafepoints -H:-ParseRuntimeOptions -H:-IncludeMethodData --initialize-at-build-time ls -l ./example01_graalvm.bin perf stat -r 100 ./example01_graalvm.bin > /dev/null ``` -------------------------------- ### Build and Benchmark Scala Native Image Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md This snippet shows how to build a Scala Native executable, measure its startup time using `perf stat`, and interpret the performance counter output. Ensure you have the necessary tools installed and `kernel.perf_event_paranoid` is set appropriately. ```sh sudo apt install linux-tools-common linux-tools-generic clang libstdc++-12-dev libgc-dev sudo sysctl kernel.perf_event_paranoid=1 scala-cli --power package --native-version 0.5.12 perf stat -r 100 ./example01_native.bin > /dev/null ``` ```text Performance counter stats for './example01_native.bin' (100 runs): 0.81 msec task-clock # 0.801 CPUs utilized ( +- 0.22% ) 0 context-switches # 0.000 /sec 0 cpu-migrations # 0.000 /sec 732 page-faults # 900.150 K/sec ( +- 0.02% ) 5,950,991 cpu_atom/instructions/ # 1.60 insn per cycle ( +- 0.08% ) cpu_core/instructions/ (0.00%) 3,728,384 cpu_atom/cycles/ # 4.585 GHz ( +- 0.22% ) cpu_core/cycles/ (0.00%) 1,062,936 cpu_atom/branches/ # 1.307 G/sec ( +- 0.08% ) cpu_core/branches/ (0.00%) 7,488 cpu_atom/branch-misses/ # 0.70% of all branches ( +- 1.09% ) cpu_core/branch-misses/ (0.00%) 0.00101568 +- 0.00000732 seconds time elapsed ( +- 0.72% ) ``` -------------------------------- ### Run JVM benchmarks with perf profiler (specific events) Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Benchmark with a specified list of `perf` events and a set number of threads. This example uses 16 threads to check for CPU stalls and includes detailed event specifications. ```sh sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -t 16 -prof "perfnorm:event=cycles,instructions,uops_executed.core,uops_executed.stall_cycles,cache-references,cache-misses,cycle_activity.stalls_total,cycle_activity.stalls_mem_any,cycle_activity.stalls_l3_miss,cycle_activity.stalls_l2_miss,cycle_activity.stalls_l1d_miss" .*' ``` -------------------------------- ### Run JVM benchmarks with perf profiler (CPU events) Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md On Linux, use the `perf` profiler to analyze CPU event statistics normalized per operation. This example focuses on `TwitterAPIReading.jsoniterScala`. ```sh sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof perfnorm TwitterAPIReading.jsoniterScala' ``` -------------------------------- ### Run JVM benchmarks with JFR profiler Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Use the JFR profiler to get benchmark results with an in-flight recording file. Specify the output directory, warm-up iterations, and duration. ```sh sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof "jfr:dir=target/jfr-reports" -wi 10 -i 60 TwitterAPIReading.jsoniterScala' ``` -------------------------------- ### List Async Profiler events for a running Java process Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md After starting your Java application or benchmark, use `jps` to find the process ID (PID). Then, use this command with the profiler script and PID to list available events. ```sh $/opt/async-profiler/profiler.sh list 6924 ``` -------------------------------- ### Generate Custom Tagged Union Codec in Scala Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Use `def` methods for codec generation to avoid duplicated codec instances in Scala 3. This example demonstrates creating a custom codec for a tagged union type `NodeId`. ```scala object Tags { opaque type Tagged[+V, +T] = Any type @@[+V, +T] = V & Tagged[V, T] def tag[T]: [V] => V => V @@ Tag = [V] => (v: V) => v } object Graph { import Tags.{@@, tag} def tagJsonValueCodec[V, T](codec: JsonValueCodec[V]): JsonValueCodec[V @@ T] = new JsonValueCodec[V @@ T]: //println("+1") override def decodeValue(in: JsonReader, default: V @@ T): V @@ T = tag[T](codec.decodeValue(in, default: V)) override def encodeValue(x: V @@ T, out: JsonWriter): Unit = codec.encodeValue(x, out) override def nullValue: V @@ T = tag[T](codec.nullValue) trait NodeIdTag type NodeId = Int @@ NodeIdTag case class Node(id: NodeId, name: String) case class Edge(node1: NodeId, node2: NodeId) given JsonValueCodec[Graph.NodeId] = Graph.tagJsonValueCodec(JsonCodecMaker.make) given JsonValueCodec[Graph.Node] = JsonCodecMaker.make given JsonValueCodec[Graph.Edge] = JsonCodecMaker.make } ``` -------------------------------- ### Build and Measure Node.js Startup Time Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Builds a Scala.js release file, prints its size, and measures its startup time using 'perf stat' with Node.js. Requires Node.js and 'nvm' for version management. ```sh curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash source ~/.bashrc nvm install 22 sudo sysctl kernel.perf_event_paranoid=1 scala-cli --power package --js --js-mode release example01.sc --force -o example01.js ls -l ./example01.js perf stat -r 100 node ./example01.js > /dev/null ``` ```text Performance counter stats for 'node ./example01.js' (100 runs): 17.64 msec task-clock # 0.994 CPUs utilized ( +- 0.14% ) 18 context-switches # 1.021 K/sec ( +- 1.43% ) 2 cpu-migrations # 113.401 /sec ( +- 2.30% ) 2,760 page-faults # 156.494 K/sec ( +- 0.01% ) 170,140,863 cpu_atom/instructions/ # 2.12 insn per cycle ( +- 0.01% ) cpu_core/instructions/ ( +- 26.12% ) (0.00%) 80,128,642 cpu_atom/cycles/ # 4.543 GHz ( +- 0.14% ) cpu_core/cycles/ ( +- 26.44% ) (0.00%) 28,956,452 cpu_atom/branches/ # 1.642 G/sec ( +- 0.01% ) cpu_core/branches/ ( +- 25.84% ) (0.00%) 560,195 cpu_atom/branch-misses/ # 1.93% of all branches ( +- 0.04% ) cpu_core/branch-misses/ ( +- 24.67% ) (0.00%) 0.0177346 +- 0.0000278 seconds time elapsed ( +- 0.16% ) ``` -------------------------------- ### Run JVM benchmarks with profiler help Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Use this command to print help information for a specific profiler. Replace `` with the actual profiler name. ```sh sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof :help' ``` -------------------------------- ### Build Scala JS Wasm, Measure Startup Time with Node Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Builds Scala code to JavaScript with Wasm support using Scala-cli, then measures its startup time using Node.js and `perf`. ```sh curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash source ~/.bashrc nvm install 22 sudo sysctl kernel.perf_event_paranoid=1 scala-cli --power package --js --js-mode release --js-emit-wasm --js-module-kind es --js-module-split-style fewestmodules example01.sc --force ls -l ./example01.js/ perf stat -r 100 node --experimental-wasm-exnref ./example01.js/main.js > /dev/null ``` -------------------------------- ### Run JVM benchmarks with Async Profiler Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Execute benchmarks using the Async Profiler, specifying the JVM home, profiler settings (directory, interval, output format, library path), JVM arguments, and benchmark parameters. ```sh sbt -java-home /usr/lib/jvm/jdk-21 jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof "async:dir=target/async-reports;interval=1000000;output=flamegraph;libPath=/opt/async-profiler/lib/libasyncProfiler.so" -jvmArgsAppend "-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints" --p size=128 -wi 5 -i 10 jsoniterScala' ``` -------------------------------- ### Run Scala.js Benchmarks Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Build and run Scala.js benchmarks using sbt. Requires JDK 17+. ```sh sbt -DassemblyJSBenchmarks -java-home /usr/lib/jvm/jdk-17 +jsoniter-scala-benchmarkJS/fullOptJS ``` -------------------------------- ### Open Scala.js Benchmark Results Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Navigate to the directory containing Scala.js benchmark results and open the HTML files in a browser. ```sh cd jsoniter-scala-benchmark/js open scala-3-fullopt.html open scala-2.13-fullopt.html ``` -------------------------------- ### Run JVM benchmarks with hsdis profiler (assembly) Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Profile and print assembly code for hot methods using the `perfasm` profiler. This requires the `hsdis` library to be set up. Adjust warm-up and iteration counts as needed. ```sh sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof perfasm -wi 10 -i 10 -p size=128 BigIntReading.jsoniterScala' ``` -------------------------------- ### Build and Run GraalVM Native Image Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Builds a GraalVM native image using scala-cli, prints its size, and measures its execution time for JSON validation. ```shell scala-cli --power package --graalvm-jvm-id graalvm-oracle:24 --native-image example02.sc --force -o example02_graalvm.bin -- --no-fallback --gc=epsilon -O3 -H:+UnlockExperimentalVMOptions -R:MaxHeapSize=16m -H:-GenLoopSafepoints -H:-ParseRuntimeOptions -H:-IncludeMethodData --initialize-at-build-time ls -l ./example02_graalvm.bin time ./example02_graalvm.bin < 2023_06_430_65B0_in_network_rates.json 2> /dev/null ``` -------------------------------- ### Build and Run Uber JAR Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Builds an uber JAR using scala-cli, prints its size, and measures its execution time for JSON validation. ```shell scala-cli --power package --assembly example02.sc --force -o example02.jar ls -l ./example02.jar time ./example02.jar -J-XX:+UnlockExperimentalVMOptions -J-XX:+UseEpsilonGC -J-Xms8m -J-Xmx8m -J-XX:+AlwaysPreTouch < 2023_06_430_65B0_in_network_rates.json 2> /dev/null ``` -------------------------------- ### Build and Run Scala Native Image Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Builds a Scala Native image using scala-cli, prints its size, and measures its execution time for JSON validation. ```shell scala-cli --power package --native-version 0.5.12 --native example02.sc --native-mode release-full --native-gc none --native-lto thin --native-multithreading=false --force -o example02_native.bin ls -l ./example02_native.bin time ./example02_native.bin < 2023_06_430_65B0_in_network_rates.json 2> /dev/null ``` -------------------------------- ### List Available JMH Benchmark Options Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Display all available options for running JMH benchmarks within the jsoniter-scala project. This command is useful for understanding and configuring benchmark runs. ```sh sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -h' ``` -------------------------------- ### Build Uber Jar and Benchmark Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Builds an uber jar using scala-cli and measures its running time. Requires OpenJDK 21. Use this for standard JVM benchmarking. ```sh scala-cli --power package --assembly example03.scala --force -o example03.jar time ./example03.jar -J-XX:+UnlockExperimentalVMOptions -J-XX:+UseEpsilonGC -J-Xms32m -J-Xmx32m -J-XX:+AlwaysPreTouch ``` ```text 9223372036854775806 real 0m11.017s user 0m11.059s sys 0m0.038s ``` -------------------------------- ### Run JVM benchmarks with GC profiler Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md To observe throughput and allocation rates, run benchmarks with the GC profiler. This command specifically targets reading operations. ```sh sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof gc .*Reading.*' ``` -------------------------------- ### List available perf profiler events Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Retrieve a list of all available events for the `perf` profiler by running this command. ```sh perf list ``` -------------------------------- ### Configure kernel parameters for Async Profiler Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Before using the Async Profiler to capture kernel frames, set the `kernel.perf_event_paranoid` and `kernel.kptr_restrict` sysctl parameters. ```sh sudo sysctl kernel.perf_event_paranoid=1 sudo sysctl kernel.kptr_restrict=0 ``` -------------------------------- ### Build Scala Native Image and Benchmark Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Builds a Scala Native image using scala-cli and measures its running time. This is useful for benchmarking native compilation performance. ```sh scala-cli --power package --native-version 0.5.12 --native example03.scala --native-mode release-full --native-gc none --native-lto thin --native-multithreading=false --force -o example03_native.bin time ./example03_native.bin ``` ```text 9223372036854775806 real 0m16.668s user 0m16.660s sys 0m0.006s ``` -------------------------------- ### Publish Locally to Maven Repo Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Clean the project and publish SNAPSHOT versions to the local Maven artifact repository. ```sh sbt clean +publishM2 ``` -------------------------------- ### Run Tests and Coverage Reports with sbt Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Execute tests and generate coverage reports for various jsoniter-scala modules using specific JVM versions. This command also checks for binary compatibility issues. ```sh sbt -java-home /usr/lib/jvm/jdk-17 ++2.13.18 clean coverage jsoniter-scala-coreJVM/test jsoniter-scala-circeJVM/test jsoniter-scala-macrosJVM/test jsoniter-scala-benchmarkJVM/test coverageReport sbt -java-home /usr/lib/jvm/jdk-11 clean +test +mimaReportBinaryIssues ``` -------------------------------- ### Release New Version Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Perform a clean release of a new version, requiring 16+GB of RAM and JDK 11. Ensure artifacts are available on Maven Central before pushing changes. ```sh sbt -java-home /usr/lib/jvm/jdk-11 -J-Xmx16g clean release ``` -------------------------------- ### Publish Locally to Ivy Repo Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Clean the project and publish SNAPSHOT versions to the local Ivy artifact repository. ```sh sbt clean +publishLocal ``` -------------------------------- ### Merge Unpacked Benchmark Results Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Use jq to merge unpacked JSON benchmark results from browsers into a single file. ```sh jq -s '[.[][]]' firefox/*.json >firefox.json ``` -------------------------------- ### List Supported JMH Benchmark Output Formats Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Show all supported output formats for JMH benchmark results, such as CSV or JSON. This helps in choosing the desired format for storing benchmark data. ```sh sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -lrf' ``` -------------------------------- ### Fetch Git Tags for jsoniter-scala Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md When developing on a fork, ensure you fetch the git tags which are required by the sbt build. This command adds the upstream repository and fetches its tags. ```sh git remote add upstream git@github.com:plokhotnyuk/jsoniter-scala.git git fetch --tags upstream ``` -------------------------------- ### Check for Dependency Updates with sbt Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Use sbt to check for available dependency updates for both the project and its plugins. This command runs `dependencyUpdates` twice, reloading plugins in between. ```sh sbt ";dependencyUpdates; reload plugins; dependencyUpdates; reload return" ``` -------------------------------- ### Download Test Data Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Commands to download large JSON files for testing purposes. ```shell wget https://raw.githubusercontent.com/json-iterator/test-data/master/large-file.json wget https://webtpa-public-access.s3.us-west-2.amazonaws.com/subfolder/2023_06_430_65B0_in_network_rates.json.gz gunzip 2023_06_430_65B0_in_network_rates.json.gz ``` -------------------------------- ### Printing Generated Codec Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Add 'given CodecMakerConfig.PrintCodec with {}' to print the generated code for codecs. This is useful for debugging and understanding. ```scala given CodecMakerConfig.PrintCodec with {} ``` -------------------------------- ### Parsing and Serialization from/to String Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Use readFromString to parse JSON strings into Scala objects and writeToString to serialize Scala objects into JSON strings. ```scala val user = readFromString[User]("""{"name":"John","devices":[{"id":1,"model":"HTC One X"}]}""") val json = writeToString(User("John", Seq(Device(2, "iPhone X")))) ``` -------------------------------- ### Workaround for `make` Macro Compile-Time Errors Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md If you encounter compile-time errors related to the `make` macro, especially when its configuration depends on other code, try these workarounds: use `make` without parameters, isolate the `make` call in a separate object, move imports locally, or use `sbt clean compile stage` instead of `sbt clean stage`. Ensure only one version of jsoniter-scala is on the classpath. ```scala make ``` -------------------------------- ### Set CPU Governor to Performance Mode Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Ensure your CPU is operating in `performance` mode for benchmarks, not `powersave`. This script prints the current governor and then sets it to `performance` for all CPUs on Linux. ```sh cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor for i in $(ls /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor); do echo performance | sudo tee $i; done ``` -------------------------------- ### sbt Dependencies for jsoniter-scala Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Add the core and macros libraries to your sbt dependencies. Use the '%%' operator for Scala 2 and '%%%' for Scala.js/Native. ```sbt libraryDependencies ++= Seq( // Use the %%% operator instead of %% for Scala.js and Scala Native "com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-core" % "2.38.17", // Use the "provided" scope instead when the "compile-internal" scope is not supported "com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-macros" % "2.38.17" % "compile-internal" ) ``` -------------------------------- ### Deriving a Codec for a User Type Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Derive a JsonValueCodec for your top-level data structure using JsonCodecMaker.make. Intermediate codecs are derived automatically if not needed in isolation. ```scala import com.github.plokhotnyuk.jsoniter_scala.macros._ import com.github.plokhotnyuk.jsoniter_scala.core._ given userCodec: JsonValueCodec[User] = JsonCodecMaker.make ``` -------------------------------- ### List Supported JMH Profilers Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Retrieve a list of profilers supported by JMH that can be used with jsoniter-scala benchmarks. This may require entering your user password. ```sh sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -lprof' ``` -------------------------------- ### Deriving Anonymous Codecs for Generic Types (Scala 3) Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Workaround for Scala 3 compiler issues with deriving anonymous codecs for generic types. Uses named instances for codecs. ```scala case class DeResult[T](isSucceed: Boolean, data: T, message: String) case class RootPathFiles(files: List[String]) given JsonValueCodec[DeResult[Option[String]]] = JsonCodecMaker.make given JsonValueCodec[DeResult[RootPathFiles]] = JsonCodecMaker.make ``` ```scala given codecOfDeResult1: JsonValueCodec[DeResult[Option[String]]] = JsonCodecMaker.make given codecOfDeResult2: JsonValueCodec[DeResult[RootPathFiles]] = JsonCodecMaker.make ``` -------------------------------- ### Measure Disk Read Speed Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/jsoniter-scala-examples/README.md Linux command to measure the read speed of a disk, useful for understanding validation performance bottlenecks. ```shell sudo hdparm -Tt /dev/nvme0n1p4 ``` -------------------------------- ### Scala CLI Dependencies for jsoniter-scala Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Specify dependencies for Scala CLI scripts using 'dep' for the core library and 'compileOnly.dep' for the macros library. ```scala //> using dep "com.github.plokhotnyuk.jsoniter-scala::jsoniter-scala-core::2.38.17" //> using compileOnly.dep "com.github.plokhotnyuk.jsoniter-scala::jsoniter-scala-macros::2.38.17" ``` -------------------------------- ### Deriving Anonymous Codecs with Type Aliases (Scala 3) Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Alternative workaround for Scala 3 compiler issues with deriving anonymous codecs. Uses private type aliases within a trait. ```scala trait DeResultCodecs: private type DeResult1 = DeResult[Option[String]] private type DeResult2 = DeResult[RootPathFiles] given JsonValueCodec[DeResult1] = JsonCodecMaker.make given JsonValueCodec[DeResult2] = JsonCodecMaker.make end DeResultCodecs object DeResultCodecs extends DeResultCodecs import DeResultCodecs.given ``` -------------------------------- ### Clear System Cache Memory on Linux Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Improve system performance for benchmarking by clearing cache memory. This command, run with root privileges, drops caches without requiring a system reboot. ```sh sudo su free -m -h && sync && echo 3 > /proc/sys/vm/drop_caches && free -m -h ``` -------------------------------- ### Custom Codec for OffsetDateTime Parsing Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Workaround for unsupported escaped encoding of ASCII characters when parsing numeric or java.time.* values. Parses values as strings and converts them. ```scala implicit val customCodecOfOffsetDateTime: JsonValueCodec[OffsetDateTime] = new JsonValueCodec[OffsetDateTime] { private[this] val defaultCodec: JsonValueCodec[OffsetDateTime] = JsonCodecMaker.make[OffsetDateTime] private[this] val maxLen = 44 // should be enough for the longest offset date time value private[this] val pool = new ThreadLocal[Array[Byte]] { override def initialValue(): Array[Byte] = new Array[Byte](maxLen + 2) } def nullValue: OffsetDateTime = null def decodeValue(in: JsonReader, default: OffsetDateTime): OffsetDateTime = { val buf = pool.get val s = in.readString(null) val len = s.length if (len <= maxLen && { buf(0) = '"' var bits, i = 0 while (i < len) { val ch = s.charAt(i) buf(i + 1) = ch.toByte bits |= ch i += 1 } buf(i + 1) = '"' bits < 0x80 }) { try { return readFromSubArrayReentrant(buf, 0, len + 2, ReaderConfig)(defaultCodec) } catch { case NonFatal(_) => () } } in.decodeError("illegal offset date time") } def encodeValue(x: OffsetDateTime, out: JsonWriter): Unit = out.writeVal(x) } ``` -------------------------------- ### Handle Large JSON Input with Stream Parsing Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md When dealing with potentially untrusted or very long JSON inputs, it's recommended to check the input length before parsing. For arrays or whitespace-separated values, consider using `scanJsonArrayFromInputStream` or `scanJsonValuesFromInputStream` instead of `readFromStream` to manage large inputs more effectively. ```scala scanJsonArrayFromInputStream[String](in) { readFromString[String](s) } ``` ```scala scanJsonValuesFromInputStream[String](in) { readFromString[String](s) } ``` -------------------------------- ### Workaround for Nested Parsing/Serialization Errors Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md To avoid unexpected parsing or serialization errors when reusing `JsonReader` or `JsonWriter` instances in nested routines, use reentrant parsing or serialization. This approach creates a new instance of `JsonReader` or `JsonWriter` on each reentrant call, preventing issues with shared state. ```scala scanJsonValuesFromStreamReentrant[String](in) { readFromString[String](s) } ``` -------------------------------- ### Scala.js/Scala Native Enum Definition Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Defines an enum for Scala.js and Scala Native. Use this when Scala 3 enum syntax is not supported. ```scala object Level { val HIGH: Level = new Level("HIGH", 0) val LOW: Level = new Level("LOW", 1) val values: Array[Level] = Array(HIGH, LOW) def valueOf(name: String): Level = if (HIGH.name() == name) HIGH else if (LOW.name() == name) LOW else throw new IllegalArgumentException(s"Unrecognized Level name: $name") } final class Level private (name: String, ordinal: Int) extends Enum[Level](name, ordinal) ``` -------------------------------- ### Scala Case Classes for Data Structures Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Define Scala case classes to represent your JSON data structures. These are used for parsing and serialization. ```scala case class Device(id: Int, model: String) case class User(name: String, devices: Seq[Device]) ``` -------------------------------- ### Handling ADT Leaf Class Names with Dots Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Workaround for issues where the default name mapper strips names with dots in ADT leaf classes. Uses the `@named` annotation. ```scala sealed abstract class Version(val value: String) object Version { @named("8.10") case object `8.10` extends Version("8.10") @named("8.09") case object `8.09` extends Version("8.9") } ``` -------------------------------- ### Java Enum for Scala.js Compatibility Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Scala.js has limitations with Java enums. For JVM and other platforms, use standard Java enums. For Scala.js and Scala Native, consider Java enum emulation or splitting sources for different platforms. ```java public enum Level { HIGH, LOW; } ``` -------------------------------- ### Scala 3 Enum Definition Source: https://github.com/plokhotnyuk/jsoniter-scala/blob/master/README.md Defines an enum using Scala 3's native enum syntax. This is the preferred method for Scala 3 projects. ```scala enum Level extends Enum[Level] { case HIGH case LOW } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.