Is it a good practice to store a large string (over 300000 chars) in a sole String object in case of memory management and performance or there’s better way?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Johan Sjöberg’s explanation is good:
If 300,000 characters that make up your String object don’t reside in a Java source file enclosed in double quotes(” “), e.g. residing in an external file, then you can use different techniques to get the String content chunk by chunk or as a whole. Take a look at this example:
Assuming you handle possible exceptions, in the code above you get a string of size 8 bytes every time you enter the while loop. So by modifying the byte array size which is 8 in this code, you can change the chunk size and use chunks anywhere else, print them etc.
In your example, you say your string has around 300000 characters. So setting the size of the byte array
bufferto 4 x 300,000 = 1,200,000 will enable you get a single string chunk that contains all the characters.