graphql-java icon indicating copy to clipboard operation
graphql-java copied to clipboard

Cheaper assertions with constant strings

Open bbakerman opened this issue 2 years ago • 0 comments

note: This is bottom of the barrel stuff but every bit of speed or memory improvement counts right

This PR changes the assertions so we have a way to provide formatted strings to assertions without usings lambdas with closures

if you have a construct like this where variables get captured

    for (int i = 0; i < LOOPS; i++) {
            final int captured = i;
            Assert.assertTrue(true, () -> String.format("This string is not constant %d", captured));
    }

then the compiler turns that Lambda into a synthetic inner method and a new object is allocated for ever invocation. So while it runs fast - it still allocates memory for that lambda callsite.

Capto_Annotation

where as if there is not variable capture :

 for (int i = 0; i < LOOPS; i++) {
            Assert.assertTrue(true, () -> "This string is constant");
 }

Then the lamba is a singleton object and no memory allocation is made.

It therefore equals this construct in speed and memory allocation - ie none

 for (int i = 0; i < LOOPS; i++) {
            Assert.assertTrue(true, "This string is constant");
 }

All of these methods run fast and it seems equally as fast as each other however 2 dont allocate memory and one does.

This PR now allows these forms

Assert.assertTrue(x, "This string is %s", "arg1");
Assert.assertTrue(x, "This string is %s %s", "arg1", "arg2");
Assert.assertTrue(x, "This string is %s %s %s", "arg1", "arg2", "arg3");
Assert.assertTrue(x, "This string is constant");
Benchmark                                                    Mode  Cnt      Score     Error   Units
AssertBenchmark.benchMarkAssertWithString                   thrpt    9  46884.428 ± 123.573  ops/ms
AssertBenchmark.benchMarkAssertWithStringFormatted          thrpt    9  46840.646 ± 162.197  ops/ms
AssertBenchmark.benchMarkAssertWithStringSupplier           thrpt    9  46871.447 ± 113.218  ops/ms
AssertBenchmark.benchMarkAssertWithStringSupplierFormatted  thrpt    9  46878.187 ± 117.324  ops/ms

bbakerman avatar Mar 06 '24 23:03 bbakerman