Performance Comparison of Groovy 'as' Keyword and Java Conversion Methods Using JMH
This article benchmarks the Groovy 'as' type‑conversion keyword against native Java conversion methods for String‑to‑double, double‑to‑String, and double‑to‑int operations using JMH, revealing that Java's built‑in approaches consistently outperform Groovy's 'as' keyword across various test cases.
The author revisits the Groovy as keyword, which is convenient for type conversion, and evaluates its performance compared to native Java conversion methods using the Java Microbenchmark Harness (JMH).
Test Setup
JMH is used to create benchmark cases for three conversion scenarios: String → double, double → String, and double → int. Separate Groovy utility classes implement the conversions with as and with Java APIs, and JMH runs each method with several input values.
String to double
class JmhG {
static double groovy(String str) { str as double }
static double java(String str) { Double.valueOf(str) }
static double java2(String str) { str.toBigDecimal() }
}The JMH benchmark class executes each conversion method and records throughput (ops/ms). Results show that Double.valueOf(str) is the fastest, followed by the Groovy as conversion, while StringGroovyMethods#toBigDecimal varies and can be slower for long decimal strings.
Number to String
class Jmh {
static String groovy(double number) { number as String }
static String java(double number) { number + "" }
static String java2(double number) { number.toString() }
}Benchmark results indicate that Groovy’s as conversion is noticeably slower than both Java approaches, which have comparable performance. The recommendation is to use java.lang.Double#toString() (or the equivalent static method) for optimal speed.
Double to int
class JmhG {
static int groovy(double d) { d as int }
static int java(double d) { (int) d }
}Here the Groovy as conversion is dramatically slower—by tens of times—than the direct Java cast, confirming that the Groovy keyword incurs substantial overhead.
Conclusion
Across all tested scenarios, native Java conversion methods consistently outperform Groovy’s as keyword. For performance‑critical code, developers should prefer Java APIs such as Double.valueOf , Double#toString , and explicit casts, and avoid using the Groovy as keyword in hot paths.
FunTester
10k followers, 1k articles | completely useless
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.