开发者

Can I optimize these functions?

I have 3 functions (they are minimalized so they might be difficult to read) listed below - i0, t0, and is.

is() and t0() both pull data from the DOM with this line

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

would it be better to pull the data from the DOM in i0(), and then pass it to is() and t0()?

That way I would only pull data from the DOM once, but then I would need an extra variable to store it in an pass it to the two functions.

i0():

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

t开发者_如何学运维0:

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

is():

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


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) );
}

to answer your actual question, yes doing a single select on document.forms['f0'].elements will make things slightly faster in some browsers, but it's a micro-optimization that I suspect will only be faster in old browsers (IE6) due to the hash-lookup.


You can change your for loop like this to make it faster, albeit a slight optimization (Comparison to 0 is faster than comparing to other numbers):

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+"&";
    }
  }
}


I assume you are talking about optimize in time.

Long way: Everything can be optimized. Short way: Any optimization in this kind of code will be extremely low

Anyway, function is() is very similar to JQuery serialize call and it has been optimizated. Have you considered to use it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜