473,320 Members | 2,110 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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 1454
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.formname) {
| field1.value = "one";
| field2.value = "two";...
| }
|
|
| Do this:
|
| var form = document.formname;
| form.field1.value = "one";
| form.field2.value = "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 getElementsByTagName(). 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.getElementsByTagName("P");
| for (var i = 0; i < nl.length; i++) {
| p = nl[i];
| }
|
| Do this:
|
| for (var i = 0; (p = document.getElementsByTagName("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(iterations / 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.com> 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.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.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
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...
0
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...
0
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...
6
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...
3
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...
3
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...
4
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:...
15
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(...
14
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...
2
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...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.