function pointers vs direct calling in javascript

S

Sampat

Hi,
I wanted to know the performance of calling a function pointer v/s a
normal function call in javascript in a scenario where there are
multiple calls in the js to the same function. Please share your
thoughts if someone has worked on this.

Thanks,
Sampat.
 
R

RobG

Hi,
I wanted to know the performance of calling a function pointer v/s a
normal function call in javascript in a scenario where there are
multiple calls in the js to the same function. Please share your
thoughts if someone has worked on this.

I don't know what you mean by "function pointer", there is no such
term in javascript. If you mean is it better to assign a reference to
a function rather than use a long lookup chain every time, then the
answer is yes.

e.g. If you need to call the following method a number of times:

baseObj.childObj.method();


then you can assign a reference to a local variable:

var x = baseObj.childObj.method;
x();

That should be faster, but probably only if you have to call the
method more than twice within the same execution context. You will
likely only be able to measure the difference if you call the function
10,000 times or so, and users likely won't notice a difference until
you call it 100,000 times (or so).

However, if you mean by "function pointer" that you wrap a method in a
calling function like:

var x = function(){
baseObj.childObj.method();
}


then see Randy's answer.
 
D

Darko

Sampat said the following on 11/20/2007 6:24 PM:


You don't need testing to figure it out, although testing will prove it.
The function pointer is *always* going to be slower. It has to be slower
since it it doing more than a plain function call. You are telling the
browser "Do this, then do that" versus "do that" and the first will
*always* be slower.

I don't think I understand that. What's "this", and what is "that"?

Darko
 
P

Peter Michaux

Hi,
I wanted to know the performance of calling a function pointer v/s a
normal function call in javascript in a scenario where there are
multiple calls in the js to the same function. Please share your
thoughts if someone has worked on this.

My guess is that you think the second version below is using a
"function pointer". Both examples evaluate in about the same time in
my Firefox and I'm glad they do because I would be very confused if
they didn't!

----------------------------------------------------------------

function foo() {};

var tic = (new Date()).getTime();

for (var i=0; i<1e6; i++) {
foo();
}

alert((new Date()).getTime() - tic);

----------------------------------------------------------------

var foo = function() {};

var tic = (new Date()).getTime();

for (var i=0; i<1e6; i++) {
foo();
}

alert((new Date()).getTime() - tic);

----------------------------------------------------------------

In JavaScript functions are always first class data types so in the
above two examples the identifier "foo" points/refers to the function
object that is defined. The differences in the two examples are the
syntax and also when the function objects are ready to be called when
the JavaScript is first parsed and evaluated.

Peter
 
G

getsanjay.sharma

var start2=new Date();
for (var i2=0;i2<100000;i2++){
var tempVar2 = gEBI('myDiv')
var tempVar2 = null;}

Hello Randy.

A quick question, why the 'var' keyword two times? Why not just
'tempVar2 = null'? Is this so that it doesn't go out to search the
scope tree to look for 'tempVar2' or for some other reason? An
detailed explanation with any relevant links would be greatly
appreciated.

Thanks and regards,
/~STS
 
G

getsanjay.sharma

Told ya you wouldn't believe me :)
I believe you. :)
That's a possibility, although it isn't in this case.
So you mean there are cases where this would be true? Any examples?
Detailed explanation of the use of the var keyword? I am sure there is
one somewhere but I don't have a link to one. The simplest way to
remember it is that using var on a variable name in a function will
*never* alter a global variable. I always use it unless I explicitly
want to alter a global variable from within a function. The only other
time it can come into play is with inner functions and I never use them.
They give me too big a headache and I have never had a use for them.
Here is what I think of 'var', correct me if I am wrong.

'var' doesn't as such declare a variable. You don't need 'var' keyword
to *declare* variables or put them in the symbol tree in javascript.
It's just an indication to the scripting engine that 'please put this
variable in a scope which is local to this function. So saying:

var a = 10;
var a = 11;

doesn't actually create two variables or declare two variables but
refer to the same variable both the times which is 'a' which was
declared and defined using the statement 'a = 10'. Thus prepending the
variable name with 'var' separates it from the global namespace
(scope) (assuming we are not using 'with' in which case we would have
an additional scope).

Is this good enough?

Thanks and regards,
/~STS
 
G

getsanjay.sharma

A case where I wouldn't want it to go outside looking for it?

var tempVar = new Array();
//lots of entries in tempVar here

function something(){
tempVar = "...."

}

function somethingElse(){
alert('hey, where did my array go?')
}
Agreed. That is one of the reasons why I prefix globals with g_ and so
called constants with c_ .

A case where I would? The altering of a global variable, an array, or
several other things.
var myArray = new Array();

Give it some thought :)
Huh? I am confused.
It isn't that simple though.

var someVar = "global variable";
function someFunction(){
var someVar = "local variable";
someVar = "modified in the function";
alert(window['someVar'])
}

Without testing, what will the alert say, and why? Then test it and see
if you were right without testing it :)
I was able to guess the output without running it. The answer would be
'global variable' because AFAIK javascript starts searching for an
identifier from the closest scope to the most generic scope.

But then again, I might be wrong so please feel free to correct me. :)
 
R

RobG

I believe you. :)



So you mean there are cases where this would be true? Any examples?



Here is what I think of 'var', correct me if I am wrong.

'var' doesn't as such declare a variable.

Yes, it does.

A couple of things you should know:

1. Declarations are processed before any code is executed. That means
that if you don't declare variables, they don't exist until the code
is excuted, a feature that can have great significance for functions:

bar(); // No error, bar() exists when the call is executed
foo(); // Error! foo doesn't exist until the next line is executed.

var foo = function(){}; // Function statement
function bar(){} // Function declaration


2. The use of var establishes the context for the variable. Any
variable used without var will be created as a property of the global
object for that context *when the code is executed*. Note that
undeclared variables with eval may not behave as you expect.


3. Because of 1., using var on a variable multiple times within the
same scope has no effect:

var x = 3;
alert(x); // => 3
var x;
alert(x); // => 3

You don't need 'var' keyword
to *declare* variables

Yes, you do. A variable without var isn't declared, it is created as
a property of the global object when the code executes. It is
equivalent (more or less) to:

window[variableName] = 'foo';

or put them in the symbol tree in javascript.

Not sure about the term "symbol tree".

It's just an indication to the scripting engine that 'please put this
variable in a scope which is local to this function. So saying:

var a = 10;
var a = 11;

doesn't actually create two variables or declare two variables but
refer to the same variable both the times which is 'a' which was
declared and defined using the statement 'a = 10'. Thus prepending the
variable name with 'var' separates it from the global namespace
(scope) (assuming we are not using 'with' in which case we would have
an additional scope).

Is this good enough?

No. The variable a is declared twice, so before any code is executed,
a variable a is created within the scope of the declaration. When the
code is executed, a is firstly assigned a value of 10, then
immediately afterward a value of 11. The declaration is processed
once, the assignment is processed each time the code is executed.

This feature of javascript is often used where feature testing is
required - it can be done once up front and not every time the
function is called, e.g.:

Method 1 - using a function declaration:

function getText(el){
if(typeof el.textContent == 'string') {
return el.textContent;
}
if(typeof el.innerText == 'string') {
return el.innerText;
}
}


Method 2 - using a function expression:

var getText = (function(){
var el = document.getElementsByTagName('script')[0];

if (typeof el.textContent == 'string') {
return function(el){return el.textContent;};
}

if (typeof el.innerText == 'string') {
return function(el){return el.innerText;};
}
})();


The second method should be more efficient as the feature test is only
carried out once, whereas in the first it is done every time getText
is called. Note that for a production system, the above should be
extended to support browsers that haven't implemented either
textContent or innerText - I didn't included the code here for the
sake of brevity.
 
T

Thomas 'PointedEars' Lahn

obG said:
You don't need 'var' keyword to *declare* variables

Yes, you do. A variable without var isn't declared, it is created as
a property of the global object when the code executes. It is
equivalent (more or less) to:

window[variableName] = 'foo';

(Sigh. [psf 10.1] More or less; rather less. It should be

window['variableName'] = 'foo';

if that; `window' does not need to refer to the Global Object.)

IOW, a variable that is not declared with `var' is not a variable at all.
The identifier will refer to a property of an object O in the Scope Chain.
O is often the Global Object, which should be at the end of the Scope Chain,
but O does not need to. During identifier resolution, the first object that
reports to have such a property will be O.

In fact, O may be not a host object which makes this initialization-only
approach error-prone. It is known that in the MSHTML DOM IDs and names of
markup elements make up property names of an host object that is before the
Global Object in the Scope Chain which is why you get a runtime error if you
try write access to those properties.)

(Maybe I should create a template for that as people keep forgetting it even
though I post the reminder frequently.)


PointedEars
 
G

getsanjay.sharma

Thanks a lot Randy, Rob and Thomas for your enlightening. It would
take some time for all that to seep inside but when in doubt I know
where to turn to. :)

Thanks and regards,
/~STS
 
T

Thomas 'PointedEars' Lahn

Thomas said:
IOW, a variable that is not declared with `var' is not a variable at all.
The identifier will refer to a property of an object O in the Scope Chain.
O is often the Global Object, which should be at the end of the Scope Chain,
but O does not need to. During identifier resolution, the first object that
reports to have such a property will be O.

In fact, O may be not a host object which makes this initialization-only
approach error-prone. [...]

That should have either been "may not be a _native_ object" or "_may be_ a
host object_", of course. Sorry for causing confusion.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,147
Messages
2,570,835
Members
47,382
Latest member
MichaleStr

Latest Threads

Top