code efficient

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bruce Duncan

    code efficient

    I have been starting to use Javascript a lot lately and I wanted to check
    with the "group" to get your thoughts on code efficiency. First, is there a
    good site/book that talks about good and bad ways to code.
    The reason I ask is because I was just thinking about the following...whi ch
    is better and/or why?

    document.forms["myform"].elements["txtname"].value
    or
    document.myform .txtname.value

    Just looking for some insight.

    TIA
    -Bruce


  • Balaji. M.

    #2
    Re: code efficient

    I believe the second looks quite efficient.

    Since the first one has to get the object from the array (searching for
    the object).


    Bruce Duncan wrote:[color=blue]
    > I have been starting to use Javascript a lot lately and I wanted to check
    > with the "group" to get your thoughts on code efficiency. First, is there a
    > good site/book that talks about good and bad ways to code.
    > The reason I ask is because I was just thinking about the following...whi ch
    > is better and/or why?
    >
    > document.forms["myform"].elements["txtname"].value
    > or
    > document.myform .txtname.value
    >
    > Just looking for some insight.
    >
    > TIA
    > -Bruce
    >
    >[/color]

    Comment

    • Matt Kruse

      #3
      Re: code efficient

      Bruce Duncan wrote:[color=blue]
      > which is better and/or why?
      > document.forms["myform"].elements["txtname"].value
      > or
      > document.myform .txtname.value[/color]

      I did a rough timing test (see code below) and the different in execution
      time is minimal. I had to execute the loop 100,000 times just to see a
      ..9seconds difference.

      I would say the preferred way to reference elements is always:
      document.forms["myform"]["txtname"].value

      because:
      1) It doesn't rely on global references to a form, and is easy to read
      2) You can replace the strings with variable references at a later time with
      no problems or confusion
      3) php users can replace the field name with txtname[] if they wish, without
      causing errors

      I got this result on the test file below:
      3905
      3976
      3015

      <HTML>
      <HEAD>
      <TITLE></TITLE>
      <SCRIPT>
      function timeit() {
      var max = 100000;
      var start = new Date();
      for (var i=0; i<max; i++) {
      var val = document.forms["myform"]["txtname"].value;
      }
      var stop = new Date();
      var m1 = stop.getTime() - start.getTime() ;

      var start = new Date();
      for (var i=0; i<max; i++) {
      var val = document.myform .elements["txtname"].value;
      }
      var stop = new Date();
      var m2 = stop.getTime() - start.getTime() ;

      var start = new Date();
      for (var i=0; i<max; i++) {
      var val = document.myform .txtname.value;
      }
      var stop = new Date();
      var m3 = stop.getTime() - start.getTime() ;

      alert(m1+"\n"+m 2+"\n"+m3);
      }
      </SCRIPT>
      </HEAD>
      <BODY onLoad="timeit( )">

      <form name="myform">
      <input type="text" name="txtname" value="123">
      </form>

      </BODY>
      </HTML>



      --
      Matt Kruse
      Javascript Toolbox: http://www.mattkruse.com/javascript/


      Comment

      • Berislav Lopac

        #4
        Re: code efficient

        Bruce Duncan wrote:[color=blue]
        > I have been starting to use Javascript a lot lately and I wanted to
        > check with the "group" to get your thoughts on code efficiency.
        > First, is there a good site/book that talks about good and bad ways
        > to code.
        > The reason I ask is because I was just thinking about the
        > following...whi ch is better and/or why?
        >
        > document.forms["myform"].elements["txtname"].value
        > or
        > document.myform .txtname.value
        >
        > Just looking for some insight.[/color]

        I'd use:

        var field = document.getEle mentById('txtna me0);
        field.value = 'bla';

        Berislav

        --
        If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
        Groucho, Chico, and Harpo, then Usenet is Zeppo.


        Comment

        • Lasse Reichstein Nielsen

          #5
          Re: code efficient

          "Bruce Duncan" <bruce~w~duncan @~hotmail.com> writes:
          [color=blue]
          > The reason I ask is because I was just thinking about the following...whi ch
          > is better and/or why?
          >
          > document.forms["myform"].elements["txtname"].value
          > or
          > document.myform .txtname.value[/color]

          The former is better for one, very important, reason: It is correct
          according to the W3C DOM.

          The latter assumes that the form element object is a property of the
          document object, with the same name as the form.

          For all current browsers, that is almost always the case (one
          exception is Gecko browsers in standards mode and where the form has
          only an id-attribute and no name-attribute - then the form is still
          part of the forms collection, but not a property of the document
          object).

          However, there is no guarantee that future browsers will all honor
          this tradition of polluting the document object (I hope they won't,
          it's really annoying - try making a form with id="body"!)

          The former is both correct according to standards, meaning it will
          almost certainly work in all future browsers, *and* will work in all
          Javascript enabled browsers since Netscape 3 (Netscape 2 didn't allow
          access by name, only by number).

          /L
          --
          Lasse Reichstein Nielsen - lrn@hotpop.com
          DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
          'Faith without judgement merely degrades the spirit divine.'

          Comment

          • Ivo

            #6
            Re: code efficient

            > "Bruce Duncan" writes:[color=blue][color=green]
            > > The reason I ask is because I was just thinking about the[/color][/color]
            following...whi ch[color=blue][color=green]
            > > is better and/or why?
            > > document.forms["myform"].elements["txtname"].value
            > > or
            > > document.myform .txtname.value[/color][/color]

            "Lasse Reichstein Nielsen" wrote[color=blue]
            > The former is better for one, very important, reason: It is correct
            > according to the W3C DOM.
            >
            > The latter assumes that the form element object is a property of the
            > document object, with the same name as the form.[/color]

            For the sake of efficiency only, complying with the W3C DOM can hardly be an
            argument.
            However, if a script encounters document.forms["myform"] , it immediately
            knows where to look for myform, while document.myform will make it look
            for myform in every branch until it finds it in the forms collection.
            Ivo


            Comment

            • Randy Webb

              #7
              Re: code efficient

              Balaji. M. wrote:

              <--top posting fixed-->
              [color=blue]
              > Bruce Duncan wrote:
              >[color=green]
              >> I have been starting to use Javascript a lot lately and I wanted to check
              >> with the "group" to get your thoughts on code efficiency. First, is
              >> there a
              >> good site/book that talks about good and bad ways to code.
              >> The reason I ask is because I was just thinking about the
              >> following...whi ch
              >> is better and/or why?
              >>
              >> document.forms["myform"].elements["txtname"].value
              >> or
              >> document.myform .txtname.value
              >>
              >> Just looking for some insight.
              >>[/color][/color]

              The "best" way, for that is the first one. As its more "cross-browser"
              and allows for ID's to be used instead of NAME's in the elements.
              [color=blue]
              > I believe the second looks quite efficient.
              >
              > Since the first one has to get the object from the array (searching for
              > the object).[/color]

              Yes, the second is technically "faster", but it has its flaws. Both ways
              do though.

              Read the FAQ with regards to top-posting.

              --
              Randy
              Chance Favors The Prepared Mind
              comp.lang.javas cript FAQ - http://jibbering.com/faq/

              Comment

              • Randy Webb

                #8
                Re: code efficient

                Berislav Lopac wrote:
                [color=blue]
                > Bruce Duncan wrote:
                >[color=green]
                >>I have been starting to use Javascript a lot lately and I wanted to
                >>check with the "group" to get your thoughts on code efficiency.
                >>First, is there a good site/book that talks about good and bad ways
                >>to code.
                >>The reason I ask is because I was just thinking about the
                >>following...w hich is better and/or why?
                >>
                >>document.form s["myform"].elements["txtname"].value
                >>or
                >>document.myfo rm.txtname.valu e
                >>
                >>Just looking for some insight.[/color]
                >
                >
                > I'd use:
                >
                > var field = document.getEle mentById('txtna me0);
                > field.value = 'bla';
                >
                > Berislav[/color]

                And then wonder why it breaks in certain browsers? NN4.xx comes to mind
                first. I am sure there are more, especially IE4, since it doesn't
                support getElementById (natively anyway)


                --
                Randy
                Chance Favors The Prepared Mind
                comp.lang.javas cript FAQ - http://jibbering.com/faq/

                Comment

                • Richard Cornford

                  #9
                  Re: code efficient

                  Bruce Duncan wrote:[color=blue]
                  > I have been starting to use Javascript a lot lately and I wanted to
                  > check with the "group" to get your thoughts on code efficiency.
                  > First, is there a good site/book that talks about good and bad ways
                  > to code.
                  > The reason I ask is because I was just thinking about the
                  > following...whi ch is better and/or why?
                  >
                  > document.forms["myform"].elements["txtname"].value
                  > or
                  > document.myform .txtname.value[/color]

                  There is more to efficiency than execution speed alone, though
                  javascript is inevitably not particularly fast in execution (being
                  interpreted) so speed of execution is worth considering. But Time taken
                  (or wasted) in maintenance contributes to efficiency, of a different
                  sort.

                  I prefer the longer form accessor syntax because it is self-documenting.
                  Given:-

                  document.myform

                  - it is not immediately obvious whether the object referred to is a
                  form, and image, and embed, an applet, an expando property of the
                  document, etc (assuming the form name does not make that obvious, as
                  "myform" probably would). While:-

                  document.forms['myform']

                  - is clearly intended to refer to a form object, and -
                  document.imgaes['myform'] - is clearly intended to refer to an IMG
                  element. The coinciding observation that the longer, collections based,
                  accessor is W3C DOM standard and back compatible with every browsers
                  known to understand javascript and forms, just adds weight to this
                  decision.

                  The longer accessor must be slower to resolve, but how significant that
                  is would be directly related to how often it needs to be resolved. Given
                  a desire to repeatedly refer to the same form control I would be
                  inclined to assign a reference to that control to a local variable on
                  the first occasion it was needed and then make subsequent references
                  relative to that variable:-

                  var formControl = document.forms["myform"].elements["txtname"];
                  formControl.val ue = 'something';
                  // etc.

                  Or, if the desire was to access different controls in the same form then
                  a reference to the form (or more likely its - elements - collection)
                  could be assigned to the local variable:-

                  var formElements = document.forms["myform"].elements;
                  formElements['txtname'].value = 'something';
                  // etc.

                  (Or, better yet, pass a function a reference to the form/elements
                  collection/form control as an argument so it doesn't need to be resolved
                  against the DOM at all.)

                  So it isn't the type of accessor used that contributes to, or detracts
                  from efficiency; if it is only used once to resolve a reference to a
                  form or its controls then the fractionally faster resolution of the
                  "shortcut" accessor becomes insignificant if presented with any
                  advantages associated with the longer, more formal, accessors.

                  Richard.


                  Comment

                  Working...