开发者

What is optimal method for accessing function parameters in javascript?

开发者 https://www.devze.com 2022-12-11 12:43 出处:网络
Of these simi开发者_如何学编程lar function definitions, what is optimal way to access arguments and why?

Of these simi开发者_如何学编程lar function definitions, what is optimal way to access arguments and why?

function DoStuff()
{
    return arguments[0] + arguments[1] + arguments[2];
}

function DoStuff(first, second, third)
{
    return first + second + third;
}

Does one allocate less memory than the other? Is one faster to access the parameter values than the other?


Here is my test:

    function Test1()
    {
        var start = new Date();
        for (var i = 0; i < 1000000; i++)
        {
            DoStuff1(i, i + 1, i + 2);
        }
        var done = new Date();

        alert(done - start);
    }

    function Test2()
    {
        var start = new Date();
        for (var i = 0; i < 1000000; i++)
        {
            DoStuff2(i, i + 1, i + 2);
        }
        var done = new Date();

        alert(done - start);
    }

    function DoStuff1()
    {
        var result = arguments[0] + arguments[1] + arguments[2];
    }

    function DoStuff2(first, second, third)
    {
        var result = first + second + third;
    }

Here are the results:

IE      FF

Test1()
2355    402
2381    395
2368    392

Test2()
504     6
507     7
505     7

I figured that test 2 would be faster but it's drastically faster. So, not only is it more readable but it's more efficient.


Forget about performance in this case and go for readability. From that perspective, option (2) is much to be preferred -- though, I'd go for more descriptive names. ;-)


The second.

Using the second, you know based on the signature exactly what is expected when you call the method. It's also far easier for maintainability in the future.


Referencing arguments[] anywhere in a function will significantly decrease performance on many browsers.


The performance difference should be fairly negligible between the two, however the readability of named parameters is a better practice. There are times when you cannot use named parameters and in those cases I typically use a big block of script to unpack arguments into named locals.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号