Hash vs flat function arguments (v4)

Revision 4 of this benchmark created on


Description

I don't like flat function pattern:

function calculateSquare(width, height, x, y, validate, typeCheck) { /* function body */ }

because usage of such function is not clear:

calculateSquare(100, 50, 10, 15, true, false);

When you see on such calling hard to say what is true and false here. But this exmaple looking much better:

calculateSquare({ width : 100, height : 50, x : 10 y : 15, validate : true, typeCheck : false });

Related article: https://gcanti.github.io/2014/09/25/six-reasons-to-define-constructors-with-only-one-argument.html

But what about performance?

Be careful also second test is available: http://jsperf.com/hash-vs-flat-function-arguments-2

Setup

// flat patter
    
    function flat_sum(first, second, third) {
      return first + second + third;
    }
    
    // hash patter
    
    function hash_sum(params) {
      return params.first + params.second + params.third;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Flat sum
for (var i = 0; i < 1000; i++) {
  flat_sum(i, i, i);
}
ready
Hash sum
for (var i = 0; i < 1000; i++) {
  hash_sum({
    first: i,
    second: i,
    third: i
  });
}
ready
cached hash
var params = {};
for (var i = 0; i < 1000; i++) {
  params.first = i;
  params.second = i;
  params.third = i;
  hash_sum(params);
}
ready
cached hash 2
var params = {first: 0, second: 0, third: 0};
for (var i = 0; i < 1000; i++) {
  params.first = i;
  params.second = i;
  params.third = i;
  hash_sum(params);
}
ready

Revisions

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