Is all this Invarient **** er... stuff, premature optimisation?

Robert Fraser fraserofthenight at gmail.com
Mon Apr 28 18:05:09 PDT 2008


Walter Bright wrote:
> Steven Schveighoffer wrote:
>> Java's String.substring(start, last) works just like slicing...
> 
> No it doesn't. It makes a copy (I don't know if this is true of *all* 
> versions of Java).

Java's 6's string.substring method (JDK 1.6.0_04, 64-bit Windows):

public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
	throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
	throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
	throw new StringIndexOutOfBoundsException(endIndex -beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
	new String(offset + beginIndex, endIndex - beginIndex, value);
}

The important part is new String(offset + beginIndex, endIndex - 
beginIndex, value) which does indeed do a "slice" of sorts (that is, it 
returns a string with the same char array backing it with a new offset 
and length). No copying of data is done.



More information about the Digitalmars-d mailing list