According to Time complexity of Java's substring() , java's substring takes linear time. Is there a faster way (may be in some cases)? I may suggest iterator, but suspect that it also takes O(n).
val s1: String = s.iterator.drop(5).mkString
But several operations on an iterator would be faster than same operations on string, right?
If you need to edit very long string, consider using data structure called Rope .
Scalaz library has Cord class which is implementation of modified version of Rope.
A
Cord
is a purely functional data structure for efficiently storing and manipulatingString
s that are potentially very long. Very similar toRope[Char]
, but with better constant factors and a simpler interface since it's specialized forString
s.
As Strings are - according to the linked question - always backed by a unique character array, substring
can't be faster than O(n). You need to copy the character data.
As for alternatives: there will at least be one operation which is O(n). In your example, that's mkString
which collects the characters in the iterator and builds a string from them.
However, I wouldn't worry about that too much. The fact that you're using a high level language means (should mean) that developer time is more valuable than CPU time for your particular task. substring
is also the canonical way to ... take a substring, so using it makes your program more readable.
EDIT: I also like this sentence (from this answer ) a lot: O(n) is O(1) if n does not grow large. What I take away from this is: you shouldn't write inefficient code, but asymptotical efficiency is not the same as real-world efficiency.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.