arguments.length vs argument presence check

Benchmark created by Premasagar Rose on


Description

When a function has an arbitrary number of arguments, is it better to check arguments.length (which may have a performance penalty) or to check the presence of an argument (an assumption is that the argument will be 'truthy' if it is present - this can be modified for other purposes).

Both tests include the arguments variable within them, but for one of the functions, arguments will only be sometimes used; the other function always uses it.

Setup

function checkArgsLength(arg1){
        if (arguments.length > 1){
            return doSomething.apply(null, arguments);
        }
        return false;
    }
    
    function checkArgPresence(arg1, arg2){
        if (arg2){
            return doSomething.apply(null, arguments);
        }
        return false;
    }
    
    function doSomething(arg1){
       return window.something = arg1;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
arguments.length
checkArgsLength(true);
ready
argument presence
checkArgPresence(true);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Premasagar Rose on