Function Context vs Parameter

JavaScript performance comparison

Test case created by Jeremy S

Info

Per SO question Benefits of function context vs parameter -- is there a performance benefit between using Object-oriented this context vs. passing the context as another parameter. May be related to this benchmark.

Preparation code

<p id="p1">Paragraph 1</p>
<p id="p2">Paragraph 2</p>
<p id="p3">Paragraph 3</p>

<script type="text/javascript">
//#region ------ OOP -------
var Para = function(id) {
  this.el = document.getElementById(id);
};
Para.prototype.append = function(text) {
  this.el.innerHTML += text;
};
Para.prototype.write = function(text) {
  this.el.innerHTML = text;
};
Para.prototype.clear = function() {
  this.el.innerHTML = '';
};
//#endregion ------ OOP -------


//#region ------ functional -------

function getPara(id) {
  return document.getElementById(id);
}
function writePara($p /* getPara(id) */, text) {
  $p.innerHTML = text;
}
function appendPara($p /* getPara(id) */, text) {
  $p.innerHTML += text;
}
function clearPara($p /* getPara(id) */, text) {
   $p.innerHTML = ''; // could reuse writePara?
}

//#endregion ------ functional -------


//#region ------ functional scoped -------

function writeParaScoped(text) {
  this.innerHTML = text;
}
function appendParaScoped(text) {
  this.innerHTML += text;
}
function clearParaScoped(text) {
  this.innerHTML = ''; // could reuse writePara?
}

//#endregion ------ functional scoped -------
</script>
<script>
Benchmark.prototype.setup = function() {
    var $$p2, $$p3, $p2, $p3, text = "a semi random string", p2 = 'p2', p3 = 'p3';
   
    // reset values
    writePara(getPara('p2'), 'Paragraph 2');
    writePara(getPara('p3'), 'Paragraph 3');
};
</script>

Preparation code output

Paragraph 1

Paragraph 2

Paragraph 3

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Object-Oriented
$$p2 = new Para(p2);
$$p2.append(text);
$$p2.clear();
$$p2.write(text);
pending…
Functional
$p2 = getPara(p2);
appendPara($p2, text);
clearPara($p2);
writePara($p2, text);
pending…
Functional Scoped
$p2 = getPara(p2);
appendParaScoped.call($p2, text);
clearParaScoped.call($p2);
writeParaScoped.call($p2, text);
pending…
Bound Scope
$p2 = getPara(p2);
appendParaScoped.bind($p2, text)();
clearParaScoped.bind($p2)();
writeParaScoped.bind($p2, text)();
pending…

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

Compare results of other browsers

0 comments

Add a comment