Algorithm question

  • Thread starter Thread starter Home Newbie
  • Start date Start date
H

Home Newbie

I have some stupid questions....

- Why would program 1 run faster than program 2? If I change the
sample_size to be a larger one, program 2 made my browser frozen!!
- What is the optimum value (1024 in this case) to use?

Program 1:
-----------
int sample_size = 5120; // 5K
for (i=0; i < (sample_size/1024); i++) {
my_buffer = "";
for (j=1; j<=1024; j++) {
my_buffer += "a";
}
my_data += my_buffer;
}

Program 2:
 
Do you know the difference between String and StringBuilder?

I'm guessing you're using something that initially allocates somewhat less
than 5120 bytes (probably only 1024 bytes) and then has to do more
allocation.

You can allocate StringBuilders to have room for the characters you're going
to add to them.
 
Program 1 creates 5 sets of strings of length 1 through 1024,
then 5 more strings length 1024 2048 3072, etc... up to 5120

(so 5125 strings)

Program 2 creates 5120 strings of lengths 1 through 5120...

Using

n(n+1) / 2, you can find that equates to:

1024(1025) / 2 characters * 5 + a nominal extra amount for Program 1 and (2.6
million characters or so)
5120(5121) / 2 characters for program 2 and (13 million characters or so).
 
Back
Top