代码之家  ›  专栏  ›  技术社区  ›  Kyle Hotchkiss

这段javascript是否效率低下?

  •  0
  • Kyle Hotchkiss  · 技术社区  · 15 年前

    我只是想知道这段javascript是否会减慢我的网站速度:

    $(function(){
     var realLink = location.href;
     $( "#nav a" ).each(
      function( intIndex ){
       String.prototype.startsWith = function(str){
        return (this.indexOf(str) === 0);
       }
       var pageLink = $(this).attr("href");
    
       if ( realLink.startsWith(pageLink) )
        $(this).parent().addClass("active");   
      }
     );
    });
    

    它只循环5-7次,我没有太多的javascript循环经验。

    5 回复  |  直到 15 年前
        1
  •  5
  •   kangax    15 年前

    这段代码没有什么本质上的错误,只是您不断地创建和分配一个函数给 String.prototype.startsWith 在一个循环中当然,这是不必要的工作,至少应该是:

    $(function(){
     var realLink = location.href;
     String.prototype.startsWith = function(str){
       return (this.indexOf(str) === 0);
     };
     $( "#nav a" ).each(
      function( intIndex ){
       var pageLink = $(this).attr("href");
       if ( realLink.startsWith(pageLink) )
        $(this).parent().addClass("active");   
      }
     );
    });
    

    我也不认为有必要 intIndex 争论在那里。它在函数中的任何地方都不能使用。

        2
  •  2
  •   Justin Niessner    15 年前

    通过将代码更改为:

    String.prototype.startsWith = function(str){
        return(this.indexOf(str) == 0);
    }
    
    $(function(){
        var realLink = location.href;
    
        $('#nav a').each(function(intIndex){
            var pageLink = $(this).attr("href");
            if(realLink.startsWith(pageLink))
                $(this).parent().addClass("active");
            });
    });
    

    它只是对 startsWith() 所以您不需要为循环的每个迭代定义它。

        3
  •  1
  •   Tobias Cohen    15 年前

    试用使用 Firebug's Profiling Feature 来衡量脚本的性能。

        4
  •  0
  •   Igor Zevaka    15 年前

    应该没问题。如果 #nav 元素不包含您应该确定的数千个链接。

    安装firebug for firefox,你可以运行配置文件。它将告诉您它在每个函数中花费了多少时间。我想这件事会以毫秒为单位。

        5
  •  0
  •   Dan Beam    15 年前

    如果在sizzle中使用^=运算符(在本例中是jquery),则基本上意味着“从该值开始”。试试这个:

    $(function(){
       $( '#nav a:not( [href^="' + startsWith + '"] )' ).addClass( 'active' );
    });
    

    并将starts更改为您选择的变量。