4 ms·
Another tip for the manual-scanners out there to make that for-loop a little bit faster: for(int i = 0, len = text.length(); i < len; i++) { // do someth
by rkalla 15y ago
Another tip for the manual-scanners out there to make that for-loop a little bit faster:
for(int i = 0, len = text.length(); i < len; i++) {
// do something
}
avoids the method call to length() in the comparison expression every time. I imagine a lot of you know this, just from time to time I run into someone that balks at what you can do inside of the old-school for headers and how flexible it can be to help make your life inside the loop a hair bit easier. (e.g. init your variable that you want to pull out)
As for this article, was excellent. I was surprised at how robust of a test suite it was; fortunately it looks like you only need to get concerned with really robust/complex search algorithms if you are working with large chunks of text and brute-force is surprisingly fast in most shorter cases.
Chalk one up for raw, unsexy CPU power ;)
- bermanoid 15y agoAssuming text is a String variable, the JVM should almost always pull the length call out of the loop anyways, since length() is merely a getter of the final 'count' field within the also-final String class (see http://www.docjar.com/html/api/java/lang/String.java.html http://www.docjar.com/html/api/java/lang/String.java.html), and hence cannot change within the loop, aside from re-assignment of the text variable itself (which is something that, IIRC, the modern JVMs should notice). In fact, that type of optimization is precisely the reason that if you want to access fields from multiple threads you need to perform some kind of synchronization or mark them volatile, if you don't then the JVM assumes that kind of optimization is allowed, by default, and it will do it in most cases. That said, if you're really in a performance critical section sometimes it doesn't usually hurt to hand-optimize like this, just in case the optimizer craps out for whatever reason and decides to skip optimizing certain sections of code (these reasons can be hard to predict).
- deleted 15y ago[deleted]