...

View Full Version : Is there an efficiency impact of using "arguments"



brothercake
11-09-2004, 12:14 AM
I mean something like this:


function something()
{
alert(arguments[0] + "," + arguments[1]);
}

Compared with doing this:


function something(arg1, arg2)
{
alert(arg1 + "," + arg2);
}

Although slightly more physical code, I'd rather use the former, because it looks neater. But are there any runtime efficiency losses doing that?

liorean
11-09-2004, 12:28 AM
I would suspect the latter of being faster by a very slight margin. However, why don't you benchmark it and see?

jkd
11-09-2004, 12:46 AM
I would assume an array-lookup cost, which is minimal. The Javascript environment would create the arguments array whether or not you use it, so you incur the (lack of) performance cost of arrayName[0] versus variableName.

But lioreans right, maybe the Javascript environment is whacky. Do benchmarks.

liorean
11-09-2004, 01:16 AM
Jason: arguments is a keyword. The engine might optimise those in a different way than identifiers. For example, there is no need for an identifier lookup on a keyword. A smart parser probably know that, so the question is whether the variable initialisation and identifier lookup is faster than doing just the array lookup and value confirmation. And I guess it depends a bit on the array implementation, too.

Roy Sinclair
11-09-2004, 05:04 PM
Test case:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Testing</title>
<script language="javascript" type="text/javascript">
function test1()
{
return arguments[0] + arguments[1];
}
function test2(a,b)
{
return a + b;
}
</script>
</head>
<body>
<script language="javascript" type="text/javascript">
var StartTime1 = new Date();
for (var i = 1; i < 300000 ; i++)
{
test1(1,i)
}
var EndTime1 = new Date();
var StartTime2 = new Date();
for (var i = 1; i < 300000 ; i++)
{
test2(1,i)
}
var EndTime2 = new Date();
document.write("<hr><b>test1 code took " + ((EndTime1.getTime() - StartTime1.getTime()) / 1000) + " seconds<\/b><br>");
document.write("<hr><b>test2 code took " + ((EndTime2.getTime() - StartTime2.getTime()) / 1000) + " seconds<\/b><br>");
</script>
</body>
</html>


Firefox results: Both functions appear approximately equivalent, with multiple executions the times change slightly with one showing as quicker during one execution while the other shows as quicker during the next.

IE Results: Test2 is significantly quicker (taking about 1/4 of the time of Test1) on a consistent basis.

brothercake
11-09-2004, 05:08 PM
Thanks man - that saves me the time :)

That's useful info then - leads me to conclude that for short scripts it doesn't matter, but for more complex scripts IE would be better off with the latter, if caring about IE is an issue at the time ...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum