473,805 Members | 2,266 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to optimize JS?

Due to circumstances beyond my immediate control, I've been put in charge of
getting some JavaScript code in place and operational ASAP. Normally, I'm a
C++ programmer, and previously have only barely fiddled w/ JS.

The good news is that I have been able to get through the JS coding and
everything is working as expected; the bad news is that it doesn't perform as
well as I'd like.

I feel that the performance problems that I'm experiencing are mainly due to
the (inefficient?) way that I'm doing some things. Unfortunately, I'm not
aware of a JS profiler, nor what specifically I should be looking at in order
to improve performance.

My target is limited to IE (current version).

So, my question is this: is there a way to reliably profile JS code? Are
there any accepted references/resources that discuss the inherent
inefficiencies of common JS coding practices?

Thanks for any info.
Jul 23 '05 #1
9 1471
Julie wrote:
Due to circumstances beyond my immediate control, I've been put in charge of
getting some JavaScript code in place and operational ASAP. Normally, I'm a
C++ programmer, and previously have only barely fiddled w/ JS.

The good news is that I have been able to get through the JS coding and
everything is working as expected; the bad news is that it doesn't perform as
well as I'd like.

I feel that the performance problems that I'm experiencing are mainly due to
the (inefficient?) way that I'm doing some things. Unfortunately, I'm not
aware of a JS profiler, nor what specifically I should be looking at in order
to improve performance.

My target is limited to IE (current version).

So, my question is this: is there a way to reliably profile JS code? Are
there any accepted references/resources that discuss the inherent
inefficiencies of common JS coding practices?

Thanks for any info.


This one includes a lot of the good advice I've seen posted in this ng:

http://www.codeproject.com/useritems/JavaScript.asp

This has some interesting approaches to looping:

http://www.websiteoptimization.com/speed/10/10-3.html

Mike

Jul 23 '05 #2
mscir wrote:

Julie wrote:
Due to circumstances beyond my immediate control, I've been put in charge of
getting some JavaScript code in place and operational ASAP. Normally, I'm a
C++ programmer, and previously have only barely fiddled w/ JS.

The good news is that I have been able to get through the JS coding and
everything is working as expected; the bad news is that it doesn't perform as
well as I'd like.

I feel that the performance problems that I'm experiencing are mainly due to
the (inefficient?) way that I'm doing some things. Unfortunately, I'm not
aware of a JS profiler, nor what specifically I should be looking at in order
to improve performance.

My target is limited to IE (current version).

So, my question is this: is there a way to reliably profile JS code? Are
there any accepted references/resources that discuss the inherent
inefficiencies of common JS coding practices?

Thanks for any info.


This one includes a lot of the good advice I've seen posted in this ng:

http://www.codeproject.com/useritems/JavaScript.asp

This has some interesting approaches to looping:

http://www.websiteoptimization.com/speed/10/10-3.html

Mike


Thanks -- those look like some good resources. It looks like it might be wise
to attempt to use the Mozilla Venkman JS profiler as well -- anyone have any
comments on that?
Jul 23 '05 #3
Julie wrote:
<snip>
... . It looks like it
might be wise to attempt to use the Mozilla Venkman JS
profiler as well -- anyone have any comments on that?


If you are writing for IE only then profiling in Mozilla will be
misleading in some respects. Javascript implementations vary and what
might prove the fastest technique for something in one might be a burden
to another.

Comparing IE and Mozilla, performance in string concatenation is very
different, with IE being about the slowest browser at concatenation,
while Mozilla is probably fastest. And resolving property accessors can
vary a lot between to two as well because IE seems to use a list-like
structure for JS objects (so the bigger the list the slower to worst
case property accessor resolution) while Mozilla uses hashtable-like
structures and is less influenced by the size of the objects.

Richard.
Jul 23 '05 #4
mscir wrote:
<snip>
This one includes a lot of the good advice I've seen posted in this
ng:

http://www.codeproject.com/useritems/JavaScript.asp

<snip>

Scattered among the good advice on that page are a number of
suggestions that bring into question its author's understanding
of javascript. Starting with:-

| Refactor to Simplify Code
| ...
| ... . Here's a simple example that replaces an assignment with an
| initialization. So instead of this:
|
| function foo() {
| var i;
| // ....
| i = 5;
| }
|
| Do this:
|
| function foo() {
| var i = 5;
| // ....
| }

- By ECMA specification I don't see any difference between these two,
so no performance improvement should be expected to follow.

The variable declaration happens during "variable initialisation" upon
entering the execution context in both cases, and the assignment
happens in the loop.
| Minimize DOM Interaction and I/O
|
| Interacting with the DOM is significantly more complicated than
| arithmetic computations, which makes it slower. When the JavaScript
| interpreter encounters a scoped object, the engine resolves the
| reference by looking up the first object in the chain and working
| its way through the next object until it finds the referenced
| property. To maximize object resolution speed, minimize the scope
| chain of objects. Each node reference within an element's scope
| chain means more lookups for the browser. Keep in mind that there
| are exceptions, like the window object, which is faster to fully
| reference. So instead of this:
|
| var link = location.href;
|
| Do this:
|
| var link = window.location .href;

Objects don't really have a scope chain (those belong to function
objects (as an internal property) and execution contexts). And the
- window - reference has no special role, it is a property of the
global object, and, as an identifier, will be resolved at the end
of a function's scope chain, exactly as - location - would. Making
the proposed second property accessor slower than the first.

| Minimize Object and Property Lookups
|
| Object-oriented techniques encourage encapsulation by tacking
| sub-nodes and methods onto objects. However, object-property
| lookups are slow, especially if there is an evaluation. So
| instead of this:
|
| for(var i = 0; i < 1000; i++)
| a.b.c.d(i);
|
| Do this:
|
| var e = a.b.c.d;
| for(var i = 0; i < 1000; i++)
| e(i);

This is a dangerous suggestion to be making given the example. The
expression - a.b.c.d(i) - is a method call (calling a - d - method on
the object referred to by - a.b.c -). Executing it as - e(i) - makes
it into a call to a function object, moving the - this - reference
from the - a.b.c - objet to the global object.

It would have been better to do:-

var e = a.b.c;
for(var i = 0; i < 1000; i++)
e.d(i);

- and keep the - this - reference of the method pointing at the
expected object.
| ...
|
| Also, accessing a named property or object requires a lookup.
| When possible, refer to the object or property directly by
| using an index into an object array. So instead of this:
|
| var form = document.f2; // refer to form by name
|
| Do this:
|
| var form = document.forms[1]; // refer to form by position

If that represents a recommendation to use indexed property accessors
over named ones then it is total rubbish as both will use the same
internal method to evaluate the property accessor, and the indexed
version will involve an additional type-conversion to string and as
a result could be slower (though HTML collections may be optimised
for indexed reference in a way that JS objects probably wont be)).
| Shorten Scope Chains
|
| ...
|
| ... . Each set of brackets
| recursively defines a new child of that scope. ...

Javascript is not block scoped.

| ...
|
| Avoid with Statements
|
| The with statement extends the scope chain temporarily with
| a computed object, executes a statement with this longer
| scope chain, and then restores the original scope chain.
| This can save you typing time, but cost you execution time.
| Each additional child node you refer to means more work for
| the browser in scanning the global namespace of your
| document. So instead of this:
|
| with (document.formn ame) {
| field1.value = "one";
| field2.value = "two";...
| }
|
|
| Do this:
|
| var form = document.formna me;
| form.field1.val ue = "one";
| form.field2.val ue = "two;
|
| Cache the object or property reference instead of using with,
| and use this variable for repeated references. with also
| has been deprecated, so it is best avoided.

This is not true either. The resolution of the property accessors
in the second case will take longer than the ones used in the - with
- statement, because the second version involves resolving - form -
against the scope chain (it will be fond on the first object on the
scope chain) and then resolving - field1 - or - field2 - as
properties of that object, which will take exactly as long as
resolving - field1 - or - field2 - on the first object in the scope
chain in the with - statement version, but the - with - statement
version does not need to resolve - form - first.

If there is a performance difference between the two it must be
entirely down to the overhead of using the - with - statement,
and the significance of that will diminish with an increase in
the number of property accessors/identifier needing to be resolved
within it.

Not that I think that - with - statements should be used, but this
is not an example of a reason for not using them (at least as stated).

| Access NodeLists Directly
|
| NodeLists are lists of elements from object properties like
| .childNodes and methods like getElementsByTa gName(). Because
| these objects are live (updated immediately when the
| underlying document changes), they are memory intensive and
| can take up many CPU cycles. If you need a NodeList for only
| a moment, it is faster to index directly into the list.
| Browsers are optimized to access node lists this way. So
| instead of this:
|
| nl = document.getEle mentsByTagName( "P");
| for (var i = 0; i < nl.length; i++) {
| p = nl[i];
| }
|
| Do this:
|
| for (var i = 0; (p = document.getEle mentsByTagName( "P")[i]); i++)
|
| In most cases, this is faster than caching the NodeList. In the
| second example, the browser doesn't need to create the node list
| object. It needs only to find the element at index i at that exact
| moment.

I cannot believe that this is true, it implies that it is faster to
create a new nodeList for each iteration of a loop than to create
one before the loop and then just index it in the loop.
It was also interesting to notice:-

| n = parseInt(iterat ions / 8);

- in a page on code optimisation. Math.floor should be faster than
parseInt (and more reliable) in context, and fast division by 8
with an integer result would be quickest as -

n = (iterations>>3) ;

- assuming iterations was known to be of a suitable size.

Richard.
Jul 23 '05 #5
Richard Cornford wrote:
mscir wrote:
<snip>
This one includes a lot of the good advice I've seen posted in this
ng:

http://www.codeproject.com/useritems/JavaScript.asp


<snip>

Scattered among the good advice on that page are a number of
suggestions that bring into question its author's understanding
of javascript.

<snip>

Ouch, apologies for misleading the OP. Are there any sites you recommend
regarding optimizations?

Mike

Jul 23 '05 #6
mscir wrote:

Richard Cornford wrote:
mscir wrote:
<snip>
This one includes a lot of the good advice I've seen posted in this
ng:

http://www.codeproject.com/useritems/JavaScript.asp


<snip>

Scattered among the good advice on that page are a number of
suggestions that bring into question its author's understanding
of javascript.

<snip>

Ouch, apologies for misleading the OP. Are there any sites you recommend
regarding optimizations?

Mike


Yes, now I'm more confused than before. I guess I'll stay away from the
mozilla profiler (since I won't be running on that browser), and just resort to
doing my own profiling w/ start/end time blocks after I make a change and see
if it makes an appreciable difference ...
Jul 23 '05 #7
mscir wrote:
Richard Cornford wrote: <snip>
Scattered among the good advice on that page ...

<snip> Ouch, apologies for misleading the OP. Are there any
sites you recommend regarding optimizations?


Don't get me wrong, there is a lot of valid and viable optimisation
advice on that page. It just seems that the author is expecting
javascript to be much like Java, but in many respects it is not at all
like Java. However, there remain many things that are true for all
programming languages.

For optimising javascript it has got to help to understand what should
be going on under the hood, which is where the author of that page has
fallen down slightly. For which the ECMA specification is probably the
best starting point. And then speed testing alternative approaches in
comparison with each other to see how they differ, and on many browsers
as implementations vary.

Richard.
Jul 23 '05 #8
JRS: In article <40************ ***@nospam.com> , seen in
news:comp.lang. javascript, Julie <ju***@nospam.c om> posted at Mon, 10
May 2004 11:32:23 :

I feel that the performance problems that I'm experiencing are mainly due to
the (inefficient?) way that I'm doing some things. Unfortunately, I'm not
aware of a JS profiler, nor what specifically I should be looking at in order
to improve performance.

Apart from details :

Check that you are not doing, in a step-by-step manner, something which
is implemented faster as an intrinsic operation in a suitable Object
type. Array sorting serves as an example here; and much date & random
handling.

But above all the usual rules of checking that the underlying algorithm
is well-suited, and that nothing is unnecessarily recalculated.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9

Yes, now I'm more confused than before. I guess I'll stay away from the
mozilla profiler (since I won't be running on that browser),
I won't go that far. The folks were pointing out how the performance
numbers will vary from browser to browser. It's just like profiling on
with one compiler then moving to a different compiler for production.
You would expect some variance. More of a problem would be if you used
IE specific coding of Jscript.

and just resort to
doing my own profiling w/ start/end time blocks after I make a change and see
if it makes an appreciable difference ...


Tried and true.

Robert
Jul 23 '05 #10

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

Similar topics

2
5538
by: André Næss | last post by:
Photoshop has a function called optimize to file size which tries to fit an image to some given file size. Because I need to make sure no images on a site I'm working on are larger than X KB I need something similar so that users don't have to worry so much about image file size. Does anyone know of a way to do this, preferably using ImageMagick or GD? Doing several calls to ImageMagick with different optimize settings is a not a good...
0
1801
by: Andreas Falck | last post by:
Hi, I ran the code below on two different versions, 4.0.14 and 4.0.16 respectively, both running RH 7.3 on intel. In version mysql server version 4.0.14 the SELECT privelege suffices for "optimize table", but (seemingly) the server version 4.0.16 requires INSERT as well. Is the INSERT privelege necessary for performing optimize in mysql
0
2020
by: Daniel | last post by:
Hi there, I recently came across an interesting option when right clicking on a project (Right click on the project -> properties -> Configuration Properties ->Build -> Optimize) There is an option in there to optimize the code, has anyone had any expeiance / problems with this option and were there any significant gains in performance by turning on this setting?
6
1534
by: Silly | last post by:
byte Name = new byte; uint len = (uint)Name.Length; uint err = MyFunction(devID, out Name, out len); When this code is run in release build with optimize code set to true, len is evaluated to 0. If it is run with optimize code set to false, len is evaluated as 256 (what i want). If I add an extra line of code after declaring len, like:
3
2827
by: Reddy | last post by:
The sql query for my datagrid returns 100, 000 records. But the datagrid should display 20 records per page. I am using datagrid paging, but it is taking too much time for the page to load. Is there any way I can optimize the speed. Any sample code would be great. Thanks, Reddy
3
4960
by: Sonnich | last post by:
While trying to shorten my files, I tried optimize table - later I found that I need: mysqlcheck -u root -p[password[ --all-databases --analyze --optimize (thanks to Markus Popp). But it gives this error: mysqlcheck: Got error: 1044: Access denied for user 'root'@'localhost' to database 'information_schema' when executing 'OPTIMIZE TABLE ... '
4
2035
by: Huaer.XC | last post by:
>From the following MySQL command: EXPLAIN SELECT * FROM t1 JOIN t2 ON (t1.id = t2.id) JOIN t3 ON t3.name = t1.name WHERE t1.id IN(123, 124); which result is: ------------------------------------------------------------------------------------- table type possible_key key key_len ref rows Extra t1 const PK, name PK 4 const 10 t3 const PK PK 4 const 10
15
2530
by: kenneth | last post by:
I was trying to use multiple thread to optimize my following code, but met some problems, anyone can help me? k are initialized. int computePot() { int i, j; for( i=0; i<500; i++ ) { for( j=0; j<i-1; j++ ) {
14
2539
by: andreyvul | last post by:
I have this loop (all variables are pointers): for (foo = bar; foo baz; foo--) *(foo+1) = *foo; How do I optimize the pointer swap so that it uses -- and ++ or unary +- instead of +1 (if possible - I don't want to have more #defines than code)? IOCCC winners can really help me with this :P
2
2095
by: pavanip | last post by:
Hi, I have an application like Optimize System Performance by using Memory speed, cpu speed and Disk speed. How to optimize memory speed,disk optimization and CPU optimization. Please provide me some sample source code to optimize system performance. Thanks pavani
0
9596
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
10614
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
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...
1
7649
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
6876
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
5544
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...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3847
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.