0

I am working on memory optimization of a piece of code. which is responsible for transferring an image file to other computer. Image file is 240Mb, and current app heap size is 1536Mb.

Current code is

byte[] buf = new byte[size];

while ((num = is.read(buf)) > 0) {
...
String str = new String(buf, 0, num));
...
sendToPc(str);
}

This creates a lot of string objects and when i try to push the image to more than 5 PC's it runs out of heap. So i thought of using string builder (I do not care about synchronization)

But string builder do not have a variant like

byte[] buf = new byte[size];
StringBuilder str = new StringBuilder(size); 
while ((num = is.read(buf)) > 0) { 
...
str.insert(0,buf); --> Apparently can not append byte array. 
...
str.delete(0, str.length());
}

And even if i try str.insert(0,new String(buf, 0, num)) it do not make any difference.

Any ideas, how can i squeeze the number of objects since i can not use string builder or string buffer.

Regards

Dheeraj Joshi

3 Answers 3

1

You may want to try IOUtils from the apache common io library. It provides methods to copy large files. On the same topic, the paper "The Causes of Bloat, The Limits of Health" is really instructive.

Sign up to request clarification or add additional context in comments.

Comments

1

Are you required to send the image in the sendToPc as a String? Some ByteBuffer will probabty suit better your needs ...

1 Comment

Yes. It is required. Infact. SendToPc method will call some 2 more methods and finally it transfers. So i can not modify sending part. So i need to squeeze something in computation part.
1

You should not use Strings to hold binary data. Strings contain characters. When you invoke the String constructor taking a byte array as argument, you build a string based on the default charset of the platform, which transforms the bytes into chars. The javadoc says

The behavior of this constructor when the given bytes are not valid in the default charset is unspecified

Moreover, the default charset of the sending platform is not necessarily the same as the one of the receiving platform.

Why don't you simply transfer the bytes as a byte array?

1 Comment

The problem is the code which receives this image in some other PC only accepts strings, not a byte array. And more over i do not have control over it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.