4 ms·
substring() was always defined in the 6 and 7 JavaDoc as: "Returns a new string that is a substring of this string..." Both implementations satisfy the API de
by spiralpolitik 11y ago
substring() was always defined in the 6 and 7 JavaDoc as:
"Returns a new string that is a substring of this string..."
Both implementations satisfy the API description so the API didn't change, the implementation did.
Optimizing your code based on the internals of a supposedly opaque data structure is a bad practice and if you get burned you only have yourself to blame.
- sanderjd 11y agoIt's true that they didn't violate the API documentation, but it's also true that (as your parent suggests) it probably would have been better if the API documentation had explicitly stated that `substring()` is O(1), such that this change would have been breaking. At the very least it would have made it more obvious, and at most it would have forced them to make a new method for the new behavior.
- x0x0 11y agoIn reality, performance often matters. Then there's no way to avoid needing to understand what the implementation does. The java6 implementation was a big, somewhat well-known gotcha. Read in mb of data in a String, substring a couple kb out, and tada! you're still holding all those mb. You inescapably either: 1 - substring introduces a new string, creating lots of garbage since it's an incredibly common operation, or 2 - substring saves garbage in many cases by having substring return sub-chunks of the full char array, but you will be unable to gc the full string as long as any substring remains reachable
- jaawn 11y agoor 3 - stop trusting the internal String implementation to be as efficient as possible, write a wrapper you can update with the best method for the current version, never look back :-)
- x0x0 11y agowhy not reimplement the entire standard library so you understand and control all the performance characteristics? This can be just like writing C in the 90s: start by writing a hashmap, a string, an arraylist or equivalent, etc. Because your code is sensitive to every common data structure you use.
- jaawn 11y agoBecause, most of the time, performance doesn't matter enough to justify it. Custom solutions are only necessary if you know performance is critical to your application's purpose, and that you need to squeeze as much out as possible. If that isn't the case, then you don't need to worry about the implementation details, because, in general, any performance changes won't matter.