Function Nesting with jQuery Plugin

JavaScript performance comparison

Revision 2 of this test case created by Hubert SABLONNIERE

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<a class="perf-test" href="http://net.tutsplus.com">Hi</a>
<script>
  (function() {
    function changeColor($this, value) {
      $this.css({
        color: value
      });
    }
 
    $.fn.myPlugin = function(options) {
 
      return this.each(function() {
        var $this = $(this);
 
        changeColor($this, options.color);
      });
    };
  }());
 
  (function() {
    $.fn.myPlugin2 = function(options) {
 
      return this.each(function() {
        var $this = $(this);
 
        function changeColor() {
          $this.css({
            color: options.color
          });
        }
 
        changeColor();
      });
    };
  }());

  (function() {
    $.fn.myPlugin3 = (function() {
      var changeColor = function($this, value) {
        $this.css({
          color: value
        });
      };

      return function(options) {
        return this.each(function() {
          var $this = $(this);
          changeColor($this, options.color);
        });
      }
    }());
  }());
 
  var $els = $(".perf-test");
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Optimized
$els.myPlugin({
  color: "red"
});
pending…
Unoptimized
$els.myPlugin2({
  color: "red"
});
pending…
With closure
$els.myPlugin3({
  color: "red"
});
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment