我可以优化这些功能吗?

时间:2011-07-06 22:50:18

标签: javascript optimization

下面列出了3个函数(它们最小化,因此可能难以阅读) - i0,t0和is。

is()和t0()都使用此行从DOM中提取数据

  var c=document.forms[a].elements;

最好从i0()中的DOM中提取数据,然后将其传递给is()和t0()吗?

这样我只会从DOM中提取一次数据,但是我需要一个额外的变量来存储它,然后传递给两个函数。

I0():

function i0()
  {
  if(t0())
    {
    var a=is('f0');
    s0('bi0.php',a,s2);
    }
  }

T0:

function t0()
  {
  var a=document.forms['f0'].elements;
  a1="Please enter your credentials";
  a2="That email is not registered";
  a3="Incorrect credentials - Reset your password?";
  if(c0(a,a1,'fb1')&&c2(a[1],a2,'fb1')&&c3(a[2],a3,'fb1'))
    {
    return 1;
    }
  else
    {
    return 0;
    }
  }

是():

function is(a)
  {
  var b='';
  var c=document.forms[a].elements;
  for(i=0;i<c.length;i++)
    {
    if(c[i].name)
      {
      if(c[i].type=='checkbox'&&c[i].checked==false)
        {
        b+=c[i].name+"=NULL&";
        }
      else
        {
        b+=c[i].name+"="+c[i].value+"&";
        }
      }
    }
    b=b.slice(0,-1);
  return b;
  }

3 个答案:

答案 0 :(得分:1)

function i0(a){
    t0() && (a=is('f0'), s0('bi0.php', a, s2)); // just so I can use the comma like this
}

// or

function i0(){
    t0() && s0('bio.php', is('f0'), s2);
}

function t0(){
    var a = document.forms['f0'].elements,
       a1 = "Please enter your credentials",
       a2 = "That email is not registered",
       a3 = "Incorrect credentials - Reset your password?";

    return +( c0(a,a1,'fb1') && c2(a[1],a2,'fb1') && c3(a[2],a3,'fb1') );
}

function is(a){
    var b = '',
        c = document.forms[a].elements;

    for( var i=0, l=c.length; i<l; i++ ){
        c[i].name
            ? c[i].type == 'checkbox' && !c[i].checked && b += c[i].name + '=NULL&'
            : b += c[i].name + '=' + c[i].value + '&';
    }
    return ( b = b.slice(0, -1) );
}

回答您的实际问题,是的,在document.forms['f0'].elements上进行单一选择会在某些浏览器中使某些内容 稍微 更快,但这是微观优化,我怀疑由于散列查找,旧浏览器(IE6)的速度会更快。

答案 1 :(得分:1)

您可以像这样更改for循环以使其更快,尽管略有优化 (与0比较比与其他数字相比更快):

for(i = c.length;i > 0;--i)
{
if(c[i].name)
  {
  if(c[i].type=='checkbox'&&c[i].checked==false)
    {
    b+=c[i].name+"=NULL&";
    }
  else
    {
    b+=c[i].name+"="+c[i].value+"&";
    }
  }
}

答案 2 :(得分:0)

我假设您正在谈论及时优化。

很长的路:一切都可以优化。 简短方法:此类代码中的任何优化都将非常低

无论如何,function is()与JQuery serialize 调用非常相似,并且已经过优化。你考虑过使用它吗?

相关问题