I'm using StringBuilder
, instead of String
, in my code in effort to make the code time-efficient during all that parsing & concatenation.
But when i look into its source, the substring()
method of AbstractStringBuilder
and thus StringBuilder
is returning a String
and not a StringBuilder
.
What would be the idea behind this ?
Thanks.
The reason the substring
method returns an immutable String
is that once you get a part of the string inside your StringBuilder
, it must make a copy. It cannot give you a mutable "live view" into the middle of StringBuilder
's content, because otherwise you would run into conflicts of which changes to apply to what string.
Since a copy is to be made anyway, it might as well be immutable: you can easily make it mutable if you wish by constructing a StringBuilder
around it, with full understanding that it is detached from the mutable original.
To go from one StringBuilder
to another containing a segment of the original, you could use:
StringBuilder original = ...;
StringBuilder sub = new StringBuilder().append(original, offset, length);
This could have been provided as a method of original
, but as things stand it isn't.
This aside, you should profile your code before engaging in micro-optimisations of this sort.
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.