Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save WalshyDev/65d333e5320b9df20bc09bb5b6015ee7 to your computer and use it in GitHub Desktop.
Save WalshyDev/65d333e5320b9df20bc09bb5b6015ee7 to your computer and use it in GitHub Desktop.
Finding a quick String split
The pursuit of a quick way to split a string!!
Test 1: Compiled pattern running split(String)
Test 2: String -> char array -> building string -> adding to list on split char
Test 3: Some internal Java code I nabbed! Thanks OpenJDK!
```
Test 1 took: 933ms (1071811.3612 ops/s)
Test 2 took: 782ms (1278772.3785 ops/s)
Test 3 took: 310ms (3225806.4516 ops/s)
```
So, holy crap, so I looked into good old Java internals. OpenJDK had a "fastpath" in String#split where it would split a single char regex with some nice code. That code test 3. Seems like doing indexOf and substring is actually quicker than going through the chars.
Very cool!! God I love looking and learning from Java internals.
Here's the method for anyone interested: <https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/lang/String.java#L2265>
310ms for 1 million iterations... 3.2 million iterations a second can be done with this little bit of internal code (cleaned up).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment