473,787 Members | 2,881 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Algorithm Question

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";
}


Jul 20 '05 #1
4 1295
Home Newbie wrote:
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


Jul 20 '05 #2
Brian Genisio <Br**********@y ahoo.com> writes:
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.


Something like:
function aString(n) { // n integer
var ctr = "a";
var acc = "";
while(n>0) {
if (n%2==1) {
acc += ctr;
}
ctr += ctr;
n >>= 1;
}
}

This will take time proportional to n*log(n).

Another approach uses an array to collect the string instead of appending,
and then joint the array at the end. It would be the equivalent of using a
Java StringBuffer. It won't save anything in this case (but that's because
logarithmic exponentiation is very fast). When you are just accumulating
a lot of about equal length strings, it is a good optimization.

function aStringArr(n) {
var arr = [];
while(n>0) {
n--;
arr[n]="a";
}
return arr.join("");
}

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #3
Lasse Reichstein Nielsen wrote on 01 apr 2004 in comp.lang.javas cript:
Another approach uses an array to collect the string instead of
appending, and then joint the array at the end.


I thought about that, Lasse, but in the end
a cannabis joint will slow you down.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 23 '05 #4
Lasse Reichstein Nielsen wrote:
Brian Genisio <Br**********@y ahoo.com> writes:
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.


Something like:
function aString(n) { // n integer
var ctr = "a";
var acc = "";
while(n>0) {
if (n%2==1) {
acc += ctr;
}
ctr += ctr;
n >>= 1;
}
}

This will take time proportional to n*log(n).

Another approach uses an array to collect the string instead of appending,
and then joint the array at the end. It would be the equivalent of using a
Java StringBuffer. It won't save anything in this case (but that's because
logarithmic exponentiation is very fast). When you are just accumulating
a lot of about equal length strings, it is a good optimization.

function aStringArr(n) {
var arr = [];
while(n>0) {
n--;
arr[n]="a";
}
return arr.join("");
}

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'


For the Array solution, I'd personally use:

String.prototyp e.repeat = function(n) {
var arr = [];
for (var i = 0; i < n; i++) {
arr[i] = this; // or arr.push(this); although it's probably a bit slower

}
return arr.join('');
}

Then you can just do:

var buffer = "a".repeat(5120 );

Of course, if the browser supports the Array object and the join() method on the
Array object, just use:

String.prototyp e.repeat = function(n) {
return (new Array(n + 1)).join(this);
}

var buffer = "a".repeat(5120 );
alert(buffer.le ngth + ':' + buffer.substrin g(0, 20) + '...');

--
| Grant Wagner <gw*****@agrico reunited.com>

Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
2665
by: cody | last post by:
I have to write an algorithm with must ensure that objects are put in buckets (which are always 4 in size). The objects have two properties: A and B. It is not allowed that in a bucket are objects with the same A or B value. But there can be more than one object with A = null or B = null in the bucket. Sometimes there is only one valid solution, sometimes there are more valid solutions, and sometimes there isn't a complete solution at...
10
4984
by: bpontius | last post by:
The GES Algorithm A Surprisingly Simple Algorithm for Parallel Pattern Matching "Partially because the best algorithms presented in the literature are difficult to understand and to implement, knowledge of fast and practical algorithms is not commonplace." Hume and Sunday, "Fast String Searching", Software - Practice and Experience, Vol. 21 # 11, pp 1221-48
5
3931
by: junky_fellow | last post by:
How do we calculate the complexity of an algorithm? Am i right if i say the complexity of an algorithm is the number of comparisons done in that algorithm? thanx in advance .......
12
3164
by: No Such Luck | last post by:
Hi All: I'm not sure if this is the right place to ask this question, but I couldn't find a more appropriate group. This is more of a theory question regarding an algorithm implemented in C, not necessarily a C language question. I'm trying to break up a vector into an arbitrary number of subvectors, equal (or as near to equal) in size as possible. My problem occurs when the vector is not evenly divisible by the number of subvectors...
2
2105
by: ben | last post by:
hello, i'm following an algorithm book and am stuck on an early excersise in it, not because of the c programming side of it or even the algorithm side of it, i don't think, but because of maths. i don't really understand what is expected, or really what the question means. could anyone explain what the question's after please? any help much appreciated. thanks, ben. Prove an upper bound on the number of machine instructions required to
113
12356
by: Bonj | last post by:
I was in need of an encryption algorithm to the following requirements: 1) Must be capable of encrypting strings to a byte array, and decyrpting back again to the same string 2) Must have the same algorithm work with strings that may or may not be unicode 3) Number of bytes back must either be <= number of _TCHARs in * sizeof(_TCHAR), or the relation between output size and input size can be calculated simply. Has to take into account the...
29
2266
by: Roy Gourgi | last post by:
Hi, I am new to C#. I have the same time scheduling program written in C++ and it is 5 times faster than my version in C#. Why is it so slow as I thought that C# was only a little slower than C++? What am I doing wrong? Here is my code: using System;
4
4286
by: FBM | last post by:
Hi, I am working on a program that simulates one of the elements of ATM. The simulation stores events which occurs every some milliseconds for a certain amount of time. Every time that an event is stored in a double linked list, the whole list is sorted for the next round. My problem appears when subjecting the program to heavy load, that is, when I run the simulation for more than 10,000 miliseconds (every event occurs in...
1
2737
by: vermarajeev | last post by:
Hi, EveryBody This question is really interesting one. My question is related to "STL Find Algorithm" Defination Direct from book Now my questions are
1
3112
by: almurph | last post by:
Hi everyone, Concerning the Needleman-Wunsch algorithm (cf. http://en.wikipedia.org/wiki/Needleman-Wunsch_algorithm) I have noticed a possible loop. Inside the algorithm there is an important decision making mechanism. Its a "if, else if, else if" structure like:
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9497
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10169
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6749
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.