I am trying to benchmark some code. I am sending a String msg over sockets. I want to send 100KB, 2MB, and 10MB String variables. Is there an easy way to create a variable of these sizes?
Currently I am doing this.
private static String createDataSize(int msgSize) {
String data = "a";
while(data.length() < (msgSize*1024)-6) {
data += "a";
}
return data;
}
But this takes a very long time. Is there a better way?
UPDATE:
Thanks, I am doing this now.
/**
* Creates a message of size @msgSize in KB.
*/
private static String createDataSize(int msgSize) {
// Java chars are 2 bytes
msgSize = msgSize/2;
msgSize = msgSize * 1024;
StringBuilder sb = new StringBuilder(msgSize);
for (int i=0; i<msgSize; i++) {
sb.append('a');
}
return sb.toString();
}
Java
chars are 2 bytes (16 bits unsigned) in size. So if you want 2MB you need one million characters. There are two obvious issues with your code:length()is unnecessary. Add any character to a JavaStringand it’s length goes up by 1, regardless of what the character is. Perhaps you’re confusing this with the size in bytes. It doesn’t mean that; andTo further explain (2), the String concatenation operator (
+) in Java causes a newStringto be created because JavaStrings are immutable. So:actually means:
This sometimes confuses former C++ programmers as strings work differently in C++.
So your code is actually allocating a million strings for a message size of one million. Only the last one is kept. The others are garbage that will be cleaned up but there is no need for it.
A better version is:
The key difference is that:
StringBuilderis mutable so doesn’t need to be reallocated with each change; andStringBuilderis preallocated to the right size in this code sample.Note: the astute may have noticed I’ve done:
rather than:
'a'of course is a single character,"a"is aString. You could use either in this case.However, it’s not that simple because it depends on how the bytes are encoded. Typically unless you specify it otherwise it’ll use UTF8, which is variable width characters. So one million characters might be anywhere from 1MB to 4MB in size depending on you end up encoding it and your question doesn’t contain details of that.
If you need data of a specific size and that data doesn’t matter, my advice would be to simply use a
bytearray of the right size.