Open paulszefer opened 7 years ago
Fun topic. I think replace is slow because it creates a new string after each space that it removes. I suspect something like StringBuilder.replace would be faster. Another idea is to use a Pattern and a regex, but depending on how you use it the regex may be recompiled each time.
https://stackoverflow.com/questions/7240190/remove-whitespace-chars-from-string-instance
I am keen to find out what you discover.
I used VisualVM to get an idea of which methods were the most expensive performance-wise and I found that a significant portion was due to formatting strings to remove all white space. This was generally done when a name, genus, or species was being set. The reason that this is occurring frequently enough to cause a noticeable performance issue is because I am storing a history of each state of the ecosystem. This allows for stepping back and forward in the simulation to stored states; however, it means that I am creating a copy of each state of the simulation (and a copy of each object inside of them). Now that I think about it, this may be a bigger problem.. But back to my original question:
Changing
string.replace(" ", "")
tostring.trim()
removed the performance hits; however, this means that the method cannot be sure that there are no spaces within the given strings. Is there a better way to go about this?