paulszefer / Ecosystem-Simulation

MIT License
0 stars 0 forks source link

Alternative to String.replace to remove all whitespace #6

Open paulszefer opened 7 years ago

paulszefer commented 7 years ago

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(" ", "") to string.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?

chris-thompson commented 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/5407592/replace-all-occurrences-of-substring-in-a-string-which-is-more-efficient-in-ja

https://stackoverflow.com/questions/6262397/string-replaceall-is-considerably-slower-than-doing-the-job-yourself

https://stackoverflow.com/questions/7240190/remove-whitespace-chars-from-string-instance

I am keen to find out what you discover.