Note that there are some explanatory texts on larger screens.

plurals
  1. POIs passing multiple sets of arguments as an array in JavaScript faster than multiple function calls?
    primarykey
    data
    text
    <p>After becoming slightly uncomfortable with multiple calls to the same function, with different parameters (as shown in the dom ready section of the code below), I decided to test out passing the parameters for this function by iterating through an array instead (as shown in <code>mouse_function_two</code>). To my surprise I found that <code>mouse_function_two</code> ran considerably faster.</p> <p>My question is, would <code>mouse_function_two</code> be considered better JavaScript practice than <code>mouse_function_one</code>? </p> <p>Note: I am slightly concerned I may not be using firebugs console.time utility correctly! </p> <h3>Initial attempt</h3> <pre><code>function mouse_function_one (hover_selector, class_name, add_link) { hover_item = $(hover_selector) hover_item.each(function(){ $(this).hover( function () { $(this).addClass(class_name); if ( add_link == true ) { $(this).click(function(){ var href = $(this).find('a').attr('href'); window.location.href = href; }); } else return false; }, function () { $(this).removeClass(class_name); }); }); } </code></pre> <h3>Second (faster) attempt:</h3> <pre><code>function mouse_function_two (args) { for (var i=0; i &lt; args.length; i++) { hover_selector = $(args[i][0]); class_name = args[i][1]; add_link = args[i][2]; hover_item = $(hover_selector) hover_selector.each(function(){ $(this).hover( function () { $(this).addClass(class_name); if ( add_link == true ) { $(this).click(function(){ var href = $(this).find('a').attr('href'); window.location.href = href; }); } else return false; }, function () { $(this).removeClass(class_name); }); }); } } </code></pre> <h3>Client code:</h3> <pre><code>// on dom ready $(function(){ console.time('f1'); mouse_function_one('#newsletter .right', 'hovered', true); mouse_function_one('.block-couple div.right', 'hovered', false); mouse_function_one('.bulletin', 'selected', true); console.timeEnd('f1'); //speed is calculated as 104ms args = []; args[0] = ['#newsletter .right', 'hovered', true]; args[1] = ['.block-couple div.right', 'hovered', false]; args[2] = ['.bulletin', 'selected', true]; console.time('f2'); mouse_function_two(args); console.timeEnd('f2'); //speed is calculated as 10ms }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload