Function Nesting with jQuery Plugin (v2)

Revision 2 of this benchmark created by Hubert SABLONNIERE on


Preparation HTML

<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>

Test runner

Ready to run.

Testing in
TestOps/sec
Optimized
$els.myPlugin({
  color: "red"
});
ready
Unoptimized
$els.myPlugin2({
  color: "red"
});
ready
With closure
$els.myPlugin3({
  color: "red"
});
ready

Revisions

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

  • Revision 1: published by Jeremy McPeak (Nettuts) on
  • Revision 2: published by Hubert SABLONNIERE on