Menu

#9 Improve escapeblock in PreparedStatement

open
nobody
None
5
2002-06-03
2002-06-03
No

I initially changed the escapeblock method from an
earlier release to prevent it from calling
ByteArrayOutputStream.write(int b) for each byte, which
was causing a massive performance problem when
dealing with largish byte arrays.

I have just downloaded and checked your latest release
and I see someone else has done the same thing,
although in a different way. Below I have my code for
the escape block method, I believe it is slightly better
than the new code as it does not result in the bytes
being copied twice. It simply iterates through the input
bytes looking for escaped characters and when it finds
one it then copies everything since the last escaped
character to the ByteArrayOutputStream. The only
possible problem it will have is if the input byte array
needs to have a high percentage of its bytes escaped,
but I think this is unlikely.

I have tested it and it works fine and I believe its
performance will be better than the current code, it is
definately better than the old code.

private final void escapeblock(
byte[] buf,
ByteArrayOutputStream bytesOut,
int size) {

int lastwritten = 0;
for (int i = 0; i < size; i++) {
byte b = buf[i];
if (b == '\0') {
//write stuff not yet written
if(i > lastwritten)
bytesOut.write(buf,lastwritten,i-lastwritten);
//write escape
bytesOut.write('\\');
bytesOut.write('0');
lastwritten = i+1;
}
else {
if (b == '\\' || b == '\'' || b == '"') {
//write stuff not yet written
if(i > lastwritten)
bytesOut.write(buf,lastwritten,i-lastwritten);
//write escape
bytesOut.write('\\');
lastwritten = i;//not i+1 as b wasn't written.
}
}
}
//write out remaining stuff from buffer
if(lastwritten < size)
bytesOut.write(buf,lastwritten,size-lastwritten);
}

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.