Skip to content

Instantly share code, notes, and snippets.

@WalshyDev
Last active May 6, 2022 12:27
Show Gist options
  • Save WalshyDev/2a8692155514cce0ee2518d1244256cb to your computer and use it in GitHub Desktop.
Save WalshyDev/2a8692155514cce0ee2518d1244256cb to your computer and use it in GitHub Desktop.
Java Micro-optimization Tests

Some micro-optimizations I tested. These were all ran on the same hardware, your timings may differ but the result should always be the same.

Checking if string has a char

Test

final String s = "This is some string because I'm crazy and need to micro-optimise ok? STOP JUDGING ME!";

TestTimer.testSnippet(1_000_000,
    () -> { boolean found = s.indexOf('-') != -1; },
    () -> { boolean found = s.contains("-"); }
);

Result

Starting test for code snippet

Warming up VM - Running 100000 iterations
Warm up done - Took 237932000ns (237.932ms)

Starting to test snippet #0 with 1000000 iterations...
Finished! Took 383808300ns (383.8083ms)

Starting to test snippet #1 with 1000000 iterations...
Finished! Took 868617100ns (868.6171ms)

Joining sub-array by separator

Test

 final String[] testArr = new String[] {"Some", "relatively", "long", "array", "that", "can", "be",
        "used", "for", "testing"};

TestTimer.testSnippet(1_000_000,
    () -> String.join(" ", Arrays.copyOfRange(testArr, 4, testArr.length)),
    () -> Arrays.stream(testArr).skip(4).collect(Collectors.joining(" "))
);

Result

Starting test for code snippet

Warming up VM - Running 100000 iterations
Warm up done - Took 379815000ns (379.815ms)

Starting to test snippet #0 with 1000000 iterations...
Finished! Took 310837700ns (310.8377ms)

Starting to test snippet #1 with 1000000 iterations...
Finished! Took 691270600ns (691.2706ms)

Removing predictable file extension

Test

final String fileName = "test_file.json";

TestTimer.testSnippet(1_000_000,
    () -> fileName.replace(".json", ""),
    () -> fileName.substring(0, fileName.length() - 5)
);

Result

Warming up VM - Running 100000 iterations
Warm up done - Took 208489400ns (208.4894ms)

Starting to test snippet #0 with 1000000 iterations...
Finished! Took 669259000ns (669.259ms)

Starting to test snippet #1 with 1000000 iterations...
Finished! Took 35022700ns (35.0227ms)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment