Home said:
I have some stupid questions....
- Why would program 1 run a lot faster than program 2? Can someone explain?
If I change the sample_size to be a larger one, program 2 will my
browser freeze!!
- 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:
------------
int sample_size = 5120; // 5K
for (i=0; i < sample_size; i++) {
my_data += "a";
}
Yeah, I understand why this is... Kind of quirky, but it the way strings
work in Javascript... similar to the way Java handles strings.
In Javascript, a string is immutable. This means that the data within a
string cannot be changed by an operator. So, an operator such as +=
does not append the data to the string. Instead, it makes a copy of the
string, appends the data, and assigns it to itself.
So, (my_data += "a") really is (my_data = my_data + "a").
In memory, conceptually, it is more like this:
tmp_var = my_data;
my_data = tmp_var + 1;
So, in Program 1, there is no itteration where you copy more than 1024
characters in (my_buffer += "a"), and you only ever copy more than 1024
bytes 4 times in (my_data += my_buffer).
In Program 2, once you reach 1028, you begin to be slower than Program
2, since every step you are copying 1029, 1030, 1031, etc characters per
execution. As you can see, it is a heck of a lot more than 5 times
slower.
A quicker algorithm would be to do something like:
my_buffer = "";
my_data = "";
for (j=0; j<=1024; j++)
my_buffer += "a";
for (j=0; j<=5; i++)
my_data += my_buffer;
Of course, your algorithm could get real cooky, and be a
binary-recursive algorithm, that will start with "a", and double it, and
double it, and double it, until you get where you need to go. I think
that would be the most efficient way to do it.
I hope this all makes sense.
Brian