StringTemplates deferred evaluation

Ron Pressler ron.pressler at oracle.com
Sun Mar 17 20:13:03 UTC 2024



> On 17 Mar 2024, at 17:39, Justin Spindler <justin.spindler at gmail.com> wrote:
> 
> 
> > You can get the effect you want by using Suppler objects as embedded expressions.
> 
> Sure, but that increases the amount of code that the developer needs to write pretty substantially, especially since there are no natural types for lambdas so the developer would have to assign that to a typed variable ahead of time or cast explicitly to a Supplier in the embedded expression.
> FOO."This is a test: \{(Supplier<Integer>) () -> calc(x, y, z)}"

This isn’t how logging libraries should do it. A better approach from a code perspective could be:

    public static <T> Supplier<T> defer(Supplier<T> s) { return s; }

which would be used like so:

    logger.log(RAW.”… \{defer(() -> foo(x))} …”);

But this may be an attempt (and possibly a failed one) at premature optimisation. AFAIK, C# doesn’t offer deferred evaluation, either, just deferred formatting of the message — just like raw string templates.

Finally, note that any kind of deferred evaluation requires some form of capture (and so possibly allocation in cases where the JIT doesn’t optimise it away). If you log inside a loop with `x` being the loop counter and used in a template argument, then `x` has to be captured for the log message to be correct. Furthermore, the cost of allocation with the JDK’s state-of-the-art collectors isn’t what it used be in the past.

As always, platform optimisations must be guided by actual profiles of actual applications; a 1000x optimisation cannot improve application performance by more than 1% if the optimised operation is 1% of the profile to begin with. We strive to optimise what actually needs to be optimised, not what we speculate could benefit from optimisation in artificial scenarios. The need for something like `defer` is dependent on such evaluations being empirically found to be a common bottleneck in real-world applications. Maybe the need for more code is a problem that requires addressing, and maybe it’s not a problem at all. That we could imagine it to be a problem in hypothetical applications is not sufficient to justify optimising it.

— Ron


More information about the amber-dev mailing list