override read(), leads to ~10 percent performance increase

This commit is contained in:
Lars Kühne 2002-11-03 15:03:36 +00:00
parent fb97056b9b
commit d471c9cd54
2 changed files with 61 additions and 5 deletions

View File

@ -24,7 +24,11 @@ import java.io.IOException;
/**
* A Reader that reads from an underlying String array, assuming each
* array element corresponds to one line of text.
*
* <p>
* <strong>Note: This class is not thread safe, concurrent reads might produce
* unexpected results!</strong> Checkstyle only works with one thread so
* currently there is no need to introduce synchronization here.
* </p>
* @author <a href="mailto:lkuehne@users.sourceforge.net">Lars Kühne</a>
*/
class StringArrayReader extends Reader
@ -71,9 +75,7 @@ class StringArrayReader extends Reader
/** @see Reader */
public int read(char[] aCbuf, int aOff, int aLen) throws IOException
{
if (mClosed) {
throw new IOException("already closed");
}
ensureOpen();
int retVal = 0;
@ -105,4 +107,37 @@ class StringArrayReader extends Reader
}
return retVal;
}
/** @see Reader */
public int read() throws IOException
{
if (mUnreportedNewline) {
mUnreportedNewline = false;
return '\n';
}
if (mArrayIdx < mUnderlyingArray.length
&& mStringIdx < mUnderlyingArray[mArrayIdx].length() )
{
// this is the common case,
// avoid char[] creation in super.read for performance
ensureOpen();
return mUnderlyingArray[mArrayIdx].charAt(mStringIdx++);
}
else {
// don't bother duplicating the new line handling above
// for the uncommon case
return super.read();
}
}
/** Throws an IOException if the reader has already been closed. */
private void ensureOpen() throws IOException
{
if (mClosed) {
throw new IOException("already closed");
}
}
}

View File

@ -12,7 +12,7 @@ public class StringArrayReaderTest
super(name);
}
public void testMisc()
public void testClose()
{
final StringArrayReader o = new StringArrayReader(new String[] {""});
assertNotNull(o);
@ -24,4 +24,25 @@ public class StringArrayReaderTest
catch (IOException e) {
}
}
public void testLineBreakSingleChar()
{
final StringArrayReader o = new StringArrayReader(new String[] {"a", "bc"});
try {
int a = o.read();
assertEquals('a', a);
int nl1 = o.read();
assertEquals('\n', nl1);
int b = o.read();
assertEquals('b', b);
int c = o.read();
assertEquals('c', c);
int nl2 = o.read();
assertEquals('\n', nl2);
int eof = o.read();
assertEquals(-1, eof);
}
catch (IOException ex) {
}
}
}