I'm just getting started with Java and while reading through this guide I noticed the following snippet, describing a recent update to the Junit framework.
We can now write assertion messages in a lambda in JUnit 5, allowing the lazy evaluation to skip complex message construction until needed:
@Test public void shouldFailBecauseTheNumbersAreNotEqual_lazyEvaluation() { Assertions.assertTrue( 2 == 3, () -> "Numbers " + 2 + " and " + 3 + " are not equal!"); }
As someone new to Java this feels like a large implementation just to get around string concatenation.
Are evaluating strings in Java really that slow (relative to other languages?). How does it compare to other compiled languages like C, Golang, etc..?
The point is: there is no lazy string formatting in Java.
Meaning, in languages like C you might see things such as:
#define debug_print...
( see some real world examples here )
The idea is to define a macro to which you pass a complicated string. But the compiler makes sure that code gets only generated for situations that actually that string to be present.
Meaning: when using debug_print()
, that complicated string concat that is might be required to build the messages passed to the macro call only happens when the message is really needed! The message is concatenated lazily.
In Java, we simply have no way to express that. You always have to go
if (someCondition) {
then pull together that large string
which isn't nice, especially when doing it for tracing. Some people in our group write that code, and it is just overly annoying that each and any trace statement has that leading if statement. That renders your whole code much less readable.
Therefore: this is not at all about the cost of string concats. It is about only spending the required CPU cycles if that string is truly needed.
And to answer the actual question: in the end, when that code gets invoked often enough, the JIT will turn it into carefully optimized machine code anyway. Thus: the actual string concat is not the issue.
In other words: you don't think of "performance" for Java in terms of source code. What matters is what happens at runtime, by the JIT.