I am reading a data in byte-by-byte. when i have determined that i have an entire message, i need to pass it to another function as a string. Some messages can be quite large, but the sizes vary frequently. Which implementation do you all feel is most effecient:
public test class
{
char[] buffer = new char[MAX_SIZE_7200];
int bufferIndex = 0;
void parseData(ArrayList<Byte> msg, length)
{
while (!msg.isEmpty())
{
buffer[bufferIndex++] = (char) msg.remove(0);
if (isfullmessage)
{
parseData(new String(buffer, 0, bufferIndex);
bufferIndex = 0; //restart and continue parsing data
}
}
}
}
OR:
public test class
{
List<Character> buffer = new ArrayList<Character>();
int bufferIndex = 0;
void parseData(ArrayList<Byte> msg, length)
{
while (!msg.isEmpty())
{
buffer.add((char) msg.remove(0));
if (isfullmessage)
{
StringBuilder builder = new StringBuilder(buffer.size());
for (Character ch: buffer)
{
builder.append(ch);
}
parseData(builder.toString());
buffer.clear();
}
}
}
}
OR:
public test class
{
StringBuilder buffer = new StringBuilder();
int bufferIndex = 0;
void parseData(ArrayList<Byte> msg, length)
{
while (!msg.isEmpty())
{
buffer.append((char) msg.remove(0));
if (isfullmessage)
{
parseData(builder.toString());
buffer.clear(); //some stringbuilder clear function
}
}
}
}
or is there a more efficient way. Please note that i have the variables holding my finished message outside the scope of the function since i might process data that does not contain a full message and may take multiple executions of the function to get a full message and process it.
Use StringBuilder. It supports appending characters one at a time, expands capacity as needed, and can be reset for reuse purposes.