optimizing code...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ian Richardson

    optimizing code...

    I'm writing a large Javascript application (uncompressed source around
    400K) which is doing almost all the initialisation it needs to in a
    just-in-time manner. However, I have included an option for almost all
    of this to be done when the application first starts.

    Under this circumstance, and since the last few nightly builds of
    Mozilla, I've been getting:


    Script warning:

    A script on this page is causing mozilla to run slowly. If it continues
    to run, your computer may become unresponsive.

    Do you want to abort the script?


    I think this is being displayed because of the time it's taking to start
    up rather than the amount of code it's wading through, but it's as good
    an excuse as any to look at optimizing code. [I've just realised and
    fixed one processor-intensive chunk of code which was being processed
    six times during startup; fine except the first four (possibly five,
    depending on circumstances) were completely unnecessary!]

    What I need is:

    1. A means of being able to forcibly skip this message

    2. A faster form of loop than for(x in list)

    3. A faster sort than a quicksort for a SELECT list

    4. A faster form of search - I'm currently using binary search

    5. A fast way of getting one OPTION at any point in a SELECT list moved
    to the top of the list. I'm currently using a method akin to a bubble sort.
    [Lists can be up to 1000 items...]

    I know I might be asking for the moon on a stick, but any help would be
    greatly appreciated.

    Thanks,

    Ian
  • Evertjan.

    #2
    Re: optimizing code...

    Ian Richardson wrote on 16 feb 2004 in comp.lang.javas cript:[color=blue]
    > I'm writing a large Javascript application (uncompressed source around
    > 400K) which is doing almost all the initialisation it needs to in a
    > just-in-time manner. However, I have included an option for almost all
    > of this to be done when the application first starts.
    >
    > Under this circumstance, and since the last few nightly builds of
    > Mozilla, I've been getting:
    >
    >
    > Script warning:
    >
    > A script on this page is causing mozilla to run slowly. If it continues
    > to run, your computer may become unresponsive.
    >
    > Do you want to abort the script?
    > [....][/color]

    Script engines, that is interpreted language emulators, also called
    interpreters, are not up to fast execution. Why not make a programme in a
    language that will be compiled? Then the setup time end the dynamic
    execution time will be orders of magnitude better.

    If you compress the source code of your javascript script, the setup time
    will be even longer, I suppose.

    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)

    Comment

    • Ian Richardson

      #3
      Re: optimizing code...

      Evertjan. wrote:
      [color=blue]
      > Ian Richardson wrote on 16 feb 2004 in comp.lang.javas cript:
      >[color=green]
      >>I'm writing a large Javascript application (uncompressed source around
      >>400K) which is doing almost all the initialisation it needs to in a
      >>just-in-time manner. However, I have included an option for almost all
      >>of this to be done when the application first starts.
      >>
      >>Under this circumstance, and since the last few nightly builds of
      >>Mozilla, I've been getting:
      >>
      >>
      >>Script warning:
      >>
      >>A script on this page is causing mozilla to run slowly. If it continues
      >>to run, your computer may become unresponsive.
      >>
      >>Do you want to abort the script?
      >>[....][/color]
      >
      >
      > Script engines, that is interpreted language emulators, also called
      > interpreters, are not up to fast execution. Why not make a programme in a
      > language that will be compiled? Then the setup time end the dynamic
      > execution time will be orders of magnitude better.[/color]

      The only real option is to rewrite the whole thing in Java... and I'm
      not looking forward to that!! I'd have to learn Java, first...
      [color=blue]
      > If you compress the source code of your javascript script, the setup time
      > will be even longer, I suppose.[/color]

      Taking out all the redundant comments and whitespace does actually save
      a bit of time, but nothing like enough. That's why I'm looking to
      optimize the code as much as possible.

      Ian

      Comment

      • Richard Cornford

        #4
        Re: optimizing code...

        "Ian Richardson" <zathras@chaos. org.uk> wrote in message
        news:c0pvpv$19j l07$1@ID-99375.news.uni-berlin.de...
        <snip>[color=blue]
        >What I need is:
        >1. A means of being able to forcibly skip this message[/color]

        The are no mechanisms for disabling the message from javascript. In so
        far as it can be prevented it is usually done by splitting the code up
        into chunks and executing each in sequence with setTimeout so the
        browser gets a chance to catch up with what it needs to do, and reset
        the counters it uses to measure the time a script has been running.
        [color=blue]
        >2. A faster form of loop than for(x in list)[/color]

        Of all of the - for - loop options - for(var prop in obj) - is certainly
        slowest but nobody can tell if any alternatives would be better (even
        applicable) without knowing the context of its use.
        [color=blue]
        >3. A faster sort than a quicksort for a SELECT list[/color]

        There is a big difference between a sort that tries to operate on the
        options in a select element and sorting a data structure that it used to
        build an options list. It is unlikely that anything useful can be said
        on the subject witho9ut being able to see the implementation.
        [color=blue]
        >4. A faster form of search - I'm currently using binary search[/color]

        A binary search, properly implemented, is hard to beat for speed.
        [color=blue]
        >5. A fast way of getting one OPTION at any point in a SELECT list
        > moved to the top of the list. I'm currently using a method akin
        > to a bubble sort.[/color]

        That is a bit strange as moving an item to the top of a list only
        requires that two items are considered/moved (the one that is to go to
        the top of the list and the one already there). That would imply that
        there are other criteria in the specification for the task.
        [color=blue]
        >[Lists can be up to 1000 items...][/color]

        One thousand items is not that bad, you can't expect instantaneous
        results form the browser/javascript combination but there is often room
        for improvement.
        [color=blue]
        >I know I might be asking for the moon on a stick, but any help
        >would be greatly appreciated.[/color]

        With javascript performance is often a trade off, usually exchanging
        increased memory use for performance. Generally you should aim to avoid
        doing the same thing more than once wherever practical. Apart form that
        there are lots of little things that done one way can inhibit
        performance when accumulated in a big script, but are difficult to
        generalise about and best addressed by discussing actual code. There is
        also a lot of interest on this group in optimum implementations .

        Unfortunately a 400Kb post would probably be unwelcome, a URL to an
        example page (with scripts) would be better, but you may not feel like
        rendering your work to date public. But you will not get much help with
        the specifics without showing at leas some of the relevant code (and its
        context).

        Richard.


        Comment

        • Jim Ley

          #5
          Re: optimizing code...

          On Mon, 16 Feb 2004 14:13:14 -0000, "Richard Cornford"
          <Richard@litote s.demon.co.uk> wrote:
          [color=blue][color=green]
          >>2. A faster form of loop than for(x in list)[/color]
          >
          >Of all of the - for - loop options - for(var prop in obj) - is certainly
          >slowest but nobody can tell if any alternatives would be better (even
          >applicable) without knowing the context of its use.[/color]

          It is however dangerous and best avoided.
          [color=blue][color=green]
          >>3. A faster sort than a quicksort for a SELECT list[/color]
          >
          >There is a big difference between a sort that tries to operate on the
          >options in a select element and sorting a data structure that it used to
          >build an options list.[/color]

          And you definately only want to do the 2nd one.
          [color=blue][color=green]
          >>4. A faster form of search - I'm currently using binary search[/color]
          >
          >A binary search, properly implemented, is hard to beat for speed.[/color]

          The questions all seem to not be about javascript, but about how to
          deal with lots of data, the problem is almost certainly one of data
          design, and speeding up the javascript won't solve that underlying
          issue.
          [color=blue][color=green]
          >>[Lists can be up to 1000 items...][/color]
          >
          >One thousand items is not that bad,[/color]

          Yes it is, a select list with 1000 items is unusable (which is why
          presumably he's needing to provide alternative navigation mechanisms)
          the solution is obvious, change the navigation system so a SELECT box
          never needs to have 1000 items in it!

          Jim.
          --
          comp.lang.javas cript FAQ - http://jibbering.com/faq/

          Comment

          • DU

            #6
            Re: optimizing code...

            Ian Richardson wrote:
            [color=blue]
            > I'm writing a large Javascript application (uncompressed source around
            > 400K) which is doing almost all the initialisation it needs to in a
            > just-in-time manner. However, I have included an option for almost all
            > of this to be done when the application first starts.
            >
            > Under this circumstance, and since the last few nightly builds of
            > Mozilla, I've been getting:
            >
            >
            > Script warning:
            >
            > A script on this page is causing mozilla to run slowly. If it continues
            > to run, your computer may become unresponsive.
            >
            > Do you want to abort the script?
            >
            >
            > I think this is being displayed because of the time it's taking to start
            > up rather than the amount of code it's wading through[/color]

            Is there a meaningful difference here? Is that really useful to know?
            Anyway, isn't the time to start proportional to the amount of loading to
            do and amount of execution to go through?

            , but it's as good[color=blue]
            > an excuse as any to look at optimizing code. [I've just realised and
            > fixed one processor-intensive chunk of code which was being processed
            > six times during startup; fine except the first four (possibly five,
            > depending on circumstances) were completely unnecessary!]
            >
            > What I need is:
            >
            > 1. A means of being able to forcibly skip this message
            >[/color]

            Go see a car mechanic and ask him if he could disable the leds warning
            about low oil pressure, door still opened, low battery voltage, etc..
            things like that. Do you believe that removing these warning signs and
            bells will help your car drive to remain a quiet, serene and enjoyable
            experience?

            Write this into a single javascript function:
            while(true);
            Now, wouldn't you appreciate your browser to warn you somehow about a
            very demanding function which may be abusing, hogging your own system
            resources and propose you of a way to abort such script?
            [color=blue]
            > 2. A faster form of loop than for(x in list)
            >[/color]

            If x is an extremely big number, then a javascript application is not
            recommendable for your particular webpage. A java applet might be the
            answer.
            [color=blue]
            > 3. A faster sort than a quicksort for a SELECT list
            >
            > 4. A faster form of search - I'm currently using binary search
            >
            > 5. A fast way of getting one OPTION at any point in a SELECT list moved
            > to the top of the list. I'm currently using a method akin to a bubble sort.
            >
            >[Lists can be up to 1000 items...]
            >
            > I know I might be asking for the moon on a stick, but any help would be
            > greatly appreciated.
            >
            > Thanks,
            >
            > Ian[/color]

            You're asking for help about an unidentified webpage. There is little we
            can suggest without being able to actually examine the code. There are
            many ways and techniques to make javascript functions run faster and
            there are many ways to make a webpage markup code be downloaded, parsed
            and rendered faster. There are tutorials, books, articles on all this.

            Are you familiar with memory footprint softwares and algorithmic
            theoretical works?

            DU

            Comment

            • Richard Cornford

              #7
              Re: optimizing code...

              "Jim Ley" <jim@jibbering. com> wrote in message
              news:40310cd5.1 272629@news.ind ividual.net...
              <snip>[color=blue][color=green][color=darkred]
              >>>2. A faster form of loop than for(x in list)[/color]
              >>
              >>Of all of the - for - loop options - for(var prop in obj)
              >>- is certainly slowest but nobody can tell if any alternatives
              >>would be better (even applicable) without knowing the context
              >>of its use.[/color]
              >
              >It is however dangerous and best avoided.[/color]

              I wouldn't argue with that.

              <snip>[color=blue]
              >The questions all seem to not be about javascript, but about
              >how to deal with lots of data, the problem is almost certainly
              >one of data design, and speeding up the javascript won't solve
              >that underlying issue.[/color]

              Probably, but we do see plenty of scripts where each and every form
              control property access is using an absolute property accessor and that
              alone is adding up to cripple the script.
              [color=blue][color=green][color=darkred]
              >>>[Lists can be up to 1000 items...][/color]
              >>
              >>One thousand items is not that bad,[/color]
              >
              >Yes it is, a select list with 1000 items is unusable (which is
              >why presumably he's needing to provide alternative navigation
              >mechanisms)[/color]

              Well, the browser can add those 1000 options in under half a second (on
              a 500MHz PC) but yes the resulting select element is unusable. I was
              hoping the 1000 items was an exception that had to be handled rather
              than the norm, but thanking about it all of the searching and sorting
              does imply an attempt at providing alternative navigation for the select
              list and therefor an expectation that it will never be usable in the
              normal way.
              [color=blue]
              >the solution is obvious, change the navigation system so a
              >SELECT box never needs to have 1000 items in it![/color]

              Removing the cause of a problem is a valid approach, preferably before
              writing 400Kb of code.

              Richard.


              Comment

              • Ian Richardson

                #8
                Re: optimizing code...

                Richard Cornford wrote:[color=blue]
                > "Ian Richardson" <zathras@chaos. org.uk> wrote in message
                > news:c0pvpv$19j l07$1@ID-99375.news.uni-berlin.de...
                > <snip>
                >[color=green]
                >>What I need is:
                >>1. A means of being able to forcibly skip this message[/color]
                >
                >
                > The are no mechanisms for disabling the message from javascript. In so
                > far as it can be prevented it is usually done by splitting the code up
                > into chunks and executing each in sequence with setTimeout so the
                > browser gets a chance to catch up with what it needs to do, and reset
                > the counters it uses to measure the time a script has been running.[/color]

                I'm only using this sort of technique as part of some code for loading
                additional .js files - and that's only required for Internet Explorer :-(

                I believe I've found where my code is falling down...
                [color=blue][color=green]
                >>2. A faster form of loop than for(x in list)[/color][/color]

                I've got an associative array of several hundred items used for language
                tokenisation, and I've got a for(x in list) type loop to find items in
                it. This loop is potentially called over 600 times during the startup
                sequence!!

                The code works but was one of those bits I originally implemented as a
                quick fix. Time to change this hideous system to something better,
                possibly an array of Options.
                [color=blue][color=green]
                >>3. A faster sort than a quicksort for a SELECT list
                >>4. A faster form of search - I'm currently using binary search[/color][/color]

                I don't think I'm going to easily improve on these.
                [color=blue][color=green]
                >>5. A fast way of getting one OPTION at any point in a SELECT list
                >> moved to the top of the list. I'm currently using a method akin
                >> to a bubble sort.[/color][/color]
                [color=blue]
                > That is a bit strange as moving an item to the top of a list only
                > requires that two items are considered/moved (the one that is to go to
                > the top of the list and the one already there). That would imply that
                > there are other criteria in the specification for the task.[/color]

                I'm fully populating the lists, then quicksorting the list, then
                shuffling a specified item (which could be anywhere in the list) to the
                top, preserving the sorted order of the remainder. I could change this to:

                1. put item I know I want at the top of the list first

                2. populate the list, checking that I don't put the first item in again.

                3. quicksort the list from the second item to the end.
                [color=blue][color=green]
                >>[Lists can be up to 1000 items...][/color]
                >
                >
                > One thousand items is not that bad, you can't expect instantaneous
                > results form the browser/javascript combination but there is often room
                > for improvement.[/color]

                I panicked. Some lists are up to 60 items, some 100, some around 300,
                and two are 1000. Some of these lists are numbers only, but I'm doing
                this to cut down on the amount of input validation and subsequent
                reformatting required.

                Mind you, if it's quicker (in both IE and Mozilla) to build the list
                using DOM code then replacing the list instead of using lots of
                list[list.length] = new Option(blah, blah) I'm all in favour of it. Any
                suggestions?
                [color=blue]
                > With javascript performance is often a trade off, usually exchanging
                > increased memory use for performance. Generally you should aim to avoid
                > doing the same thing more than once wherever practical. Apart form that
                > there are lots of little things that done one way can inhibit
                > performance when accumulated in a big script, but are difficult to
                > generalise about and best addressed by discussing actual code. There is
                > also a lot of interest on this group in optimum implementations .[/color]

                I'm afraid I can't post the code now but I anticipate it'll be public in
                the next few weeks (finally!). I've been doing lots of work to cut down
                on the startup time, restructuring the code to do as much just-in-time
                initialisation as possible.

                In the full version of the code it's possible to import data to preset
                certain sections, either via a .js configuration file or the query
                string, and this was forcing some of the just-in-time initialisation to
                occur immediately. When nice'n'quick Mozilla (in comparison to IE on my
                machine) started bringing up the slow script warnings I immediately
                blamed the long SELECT lists or a function being performed on them. A
                little more searching seems to have found a far more likely cause - the
                associative array of blah["name1"]...blah["nameN"] language tokens and
                the function to locate items in it.

                I'll have a look, make the changes as soon as I can, and see how much
                these two steps shave off the startup time.

                Ian

                Comment

                • Richard Cornford

                  #9
                  Re: optimizing code...

                  "Ian Richardson" <zathras@chaos. org.uk> wrote in message
                  news:c0v842$1c5 qug$1@ID-99375.news.uni-berlin.de...
                  <snip>[color=blue]
                  >I've got an associative array of several hundred items used
                  >for language tokenisation,[/color]

                  Wit javascript the term "associativ e array" is usually used to describe
                  normal javascript object behaviour. What I think about when you say
                  "language tokenisation" is unlikely to anything even similar to what you
                  mean when you use the term.
                  [color=blue]
                  >and I've got a for(x in list) type loop to find items in
                  >it. This loop is potentially called over 600 times during the
                  >startup sequence!![/color]

                  That sounds like the worst possible way of doing something that might be
                  achieved with one or two operations or, at worst, a call to a short
                  method, with the right object design.
                  [color=blue]
                  >The code works but was one of those bits I originally implemented
                  >as a quick fix. Time to change this hideous system to something
                  >better, possibly an array of Options.[/color]

                  If you mean an array of objects created with the - Option -
                  constructors, that will probably not be a good idea as they are fairly
                  heavyweight objects (particularly on DOM browsers) when the information
                  being contained would be, at most, two text strings and two boolean
                  values.

                  But you have decided to talk about code without detail, example or
                  specification so there is nothing specific that can be said on the
                  subject. The chances were good that if you had provided the specifics of
                  the date, its storage and retrieval requirements, and possibly the code
                  that you are currently using (with some test case date), someone would
                  have already posted a javascript implementation optimised for the task
                  (and there would now be a discussion going on about if, and/or how, it
                  could be better).

                  <snip>[color=blue]
                  >I'm fully populating the lists, then quicksorting the list,
                  >then shuffling a specified item (which could be anywhere in
                  >the list) to the top, preserving the sorted order of the remainder.
                  >I could change this to:[/color]
                  [color=blue]
                  > 1. put item I know I want at the top of the list first
                  >
                  > 2. populate the list, checking that I don't put the first item
                  > in again.
                  >
                  > 3. quicksort the list from the second item to the end.[/color]

                  Either of those approaches would be bad. You should not be attempting to
                  sort the options list in a select element at all. You should keep the
                  addition, removal and relocation of DOM nodes to the absolute minimum
                  necessary. The data that is used to populate the options list should be
                  stored in a form optimised to the type of operations you intend to
                  perform on it and "sorted" in, or from, that storage.

                  <snip>[color=blue]
                  >Mind you, if it's quicker (in both IE and Mozilla) to build
                  >the list using DOM code then replacing the list instead of
                  >using lots of list[list.length] = new Option(blah, blah) I'm
                  >all in favour of it. Any suggestions?[/color]

                  optionsCollecti onReference[optionsCollecti onReference.len gth] = ...

                  Is the most reliable cross-browser code for appending an option element
                  to the options collection. Reliability concerns should override
                  consideration of the speed of the operation at this stage. One of the
                  reasons for doing this only when necessary.

                  <snip>[color=blue]
                  >I'm afraid I can't post the code now but ...[/color]
                  <snip>

                  Your choice. Good luck.

                  Richard.


                  Comment

                  • Ian Richardson

                    #10
                    Re: optimizing code...

                    Richard Cornford wrote:[color=blue]
                    > "Ian Richardson" <zathras@chaos. org.uk> wrote in message
                    > news:c0v842$1c5 qug$1@ID-99375.news.uni-berlin.de...
                    > <snip>
                    >[color=green]
                    >>I've got an associative array of several hundred items used
                    >>for language tokenisation,[/color]
                    >
                    >
                    > Wit javascript the term "associativ e array" is usually used to describe
                    > normal javascript object behaviour. What I think about when you say
                    > "language tokenisation" is unlikely to anything even similar to what you
                    > mean when you use the term.[/color]

                    I was referring to "associativ e array" based upon the terminology used
                    in pages 130-132 of JavaScript: The Definitive Guide, 4th Edition.

                    I was creating an array like:

                    token["key_phrase_sta rt"] = "This is a key phrase to use on screen";
                    token["key_phrase_end "] = ", and here is another one."

                    ....and I intend to read the browser language so I can pull in files like
                    blah_messages_< browser_languag e>.js, but only after pulling in
                    blah_messages_e n.js, so I've always got a fully populated token[] array
                    and can easily spot where a translated token is missing. I could do some
                    of this server-side but, apart from being off-topic for this group, I
                    still have to prove to my colleagues that it can be done at all!

                    [I'm doing this because I fully expect that, once the application is
                    released, translations for other languages will become a priority
                    requirement.]
                    [color=blue][color=green]
                    >>and I've got a for(x in list) type loop to find items in
                    >>it. This loop is potentially called over 600 times during the
                    >>startup sequence!![/color]
                    >
                    >
                    > That sounds like the worst possible way of doing something that might be
                    > achieved with one or two operations or, at worst, a call to a short
                    > method, with the right object design.[/color]

                    You're not wrong. I was using for/in to traverse the array in one safe
                    (albeit very slow) way, when I could (and did) switch to using:

                    if(typeof token[nameX] != "undefined" ) etc...

                    Result: HUGE speed improvement!

                    I like typeof, and there's no problem for me using it given the target
                    range of browsers I'm aiming at.
                    [color=blue]
                    > If you mean an array of objects created with the - Option -
                    > constructors, that will probably not be a good idea as they are fairly
                    > heavyweight objects (particularly on DOM browsers) when the information
                    > being contained would be, at most, two text strings and two boolean
                    > values.[/color]

                    Indeed, I've created my own objects which just have the two text strings
                    instead of using Option, and this has also resulted in a slight speed
                    improvement. Note I also discovered that by using Option constructors it
                    was trimming whitespace in the .text which I definitely didn't want.
                    [color=blue]
                    > But you have decided to talk about code without detail, example or
                    > specification so there is nothing specific that can be said on the
                    > subject. The chances were good that if you had provided the specifics of
                    > the date, its storage and retrieval requirements, and possibly the code
                    > that you are currently using (with some test case date), someone would
                    > have already posted a javascript implementation optimised for the task
                    > (and there would now be a discussion going on about if, and/or how, it
                    > could be better).[/color]

                    I understand this but I'm currently caught between a rock and a hard
                    place. If I could post it I would. If I could post example code I would
                    but, being married, I don't have the luxury of spare time at home to put
                    together examples which reflect the code I'm using in the application
                    I'm developing for my employer.
                    [color=blue]
                    > <snip>
                    >[color=green]
                    >>I'm fully populating the lists, then quicksorting the list,
                    >>then shuffling a specified item (which could be anywhere in
                    >>the list) to the top, preserving the sorted order of the remainder.
                    >>I could change this to:[/color]
                    >
                    >[color=green]
                    >>1. put item I know I want at the top of the list first
                    >>
                    >>2. populate the list, checking that I don't put the first item
                    >> in again.
                    >>
                    >>3. quicksort the list from the second item to the end.[/color]
                    >
                    >
                    > Either of those approaches would be bad. You should not be attempting to
                    > sort the options list in a select element at all. You should keep the
                    > addition, removal and relocation of DOM nodes to the absolute minimum
                    > necessary. The data that is used to populate the options list should be
                    > stored in a form optimised to the type of operations you intend to
                    > perform on it and "sorted" in, or from, that storage.[/color]

                    I can't guarantee that, for different languages, the lists will be
                    initially specified in the language tokenisation files in an optimum
                    order. However, when initially building the SELECT list there's nothing
                    to stop me creating a local array of these tokens and sorting them
                    before populating the list. I'll certainly try out this one.

                    Thanks,

                    Ian

                    Comment

                    • Berislav Lopac

                      #11
                      Re: optimizing code...

                      Ian Richardson wrote:[color=blue]
                      > I'm writing a large Javascript application (uncompressed source around
                      > 400K) which is doing almost all the initialisation it needs to in a
                      > just-in-time manner. However, I have included an option for almost all
                      > of this to be done when the application first starts.
                      >
                      > Under this circumstance, and since the last few nightly builds of
                      > Mozilla, I've been getting:
                      >
                      >
                      > Script warning:
                      >
                      > A script on this page is causing mozilla to run slowly. If it
                      > continues
                      > to run, your computer may become unresponsive.
                      >
                      > Do you want to abort the script?[/color]

                      I my experience, thie above message usually appears when the program gets
                      stuck in an endless loops. Check your code for that first.

                      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

                      • Richard Cornford

                        #12
                        Re: optimizing code...

                        "Ian Richardson" <zathras@chaos. org.uk> wrote in message
                        news:c11s4p$1ah 0rv$1@ID-99375.news.uni-berlin.de...
                        <snip>[color=blue][color=green]
                        >>... the term "associativ e array" is usually used to
                        >>describe normal javascript object behaviour. ...[/color][/color]
                        <snip>[color=blue]
                        >I was referring to "associativ e array" based upon the
                        >terminology used in pages 130-132 of JavaScript: The
                        >Definitive Guide, 4th Edition.
                        >
                        >I was creating an array like:
                        >
                        >token["key_phrase_sta rt"] = "This is a key phrase to use on screen";
                        >token["key_phrase_end "] = ", and here is another one."[/color]

                        That is what I thought. "associativ e array" is used to describe an
                        application of javascript objects as a flexible means of storing
                        key/value pairs. It is not javascript terminology as such, and not
                        really different form borrowing "HashTable" from Java to describe the
                        concept. It suffers as terminology because it encourages people to use
                        Array objects for its implementation (which works because of the
                        objectness of Arrays) when the behaviour of Object objects is enough for
                        the task.

                        In many cases the initial definition of such an object would be better
                        achieved with an object literal:-

                        var token = {
                        key_phrase_star t:"This is a key phrase to use on screen",
                        key_phrase_end: ", and here is another one."
                        };

                        <snip>[color=blue]
                        >[I'm doing this because I fully expect that, once the
                        >application is released, translations for other languages
                        >will become a priority requirement.][/color]

                        Language negotiation is within the capabilities of the server and a task
                        that probably should be done there.

                        <snip>[color=blue]
                        >if(typeof token[nameX] != "undefined" ) etc...
                        >
                        >Result: HUGE speed improvement!
                        >
                        >I like typeof, and there's no problem for me using it
                        >given the target range of browsers I'm aiming at.[/color]

                        If the values in - token - are always non-empty strings then you will
                        probably achieve another performance improvement changing the - typeof -
                        test, with its string comparison operation, replacing it with a
                        type-converting test:-

                        if(token[nameX]){
                        ...
                        }

                        - The - if - test must resolve its expression to a boolean value, which
                        it will do by internally type-converting the value of - token[nameX] -
                        to boolean. Non-empty strings type-convert to boolean true while
                        undefined values type-convert to boolean false.

                        <snip>[color=blue]
                        >I understand this but I'm currently caught between a rock
                        >and a hard place. If I could post it I would. If I could
                        >post example code I would but, being married, I don't have
                        >the luxury of spare time at home to put together examples
                        >which reflect the code I'm using in the application I'm
                        >developing for my employer.[/color]
                        <snip>

                        (copyright issues aside) time spent solving a problem associated with a
                        project should be a valid part of a software authoring process (and so
                        funded) even if that time is spent trying to make it easy for someone
                        else to solve the problem. I can appreciate that the management in
                        charge of the budget may not see it that way.

                        Richard.


                        Comment

                        • Ian Richardson

                          #13
                          Re: optimizing code...

                          Richard Cornford wrote:

                          <snip>
                          [color=blue][color=green]
                          >>I was referring to "associativ e array" based upon the
                          >>terminology used in pages 130-132 of JavaScript: The
                          >>Definitive Guide, 4th Edition.
                          >>
                          >>I was creating an array like:
                          >>
                          >>token["key_phrase_sta rt"] = "This is a key phrase to use on screen";
                          >>token["key_phrase_end "] = ", and here is another one."[/color]
                          >
                          >
                          > That is what I thought. "associativ e array" is used to describe an
                          > application of javascript objects as a flexible means of storing
                          > key/value pairs. It is not javascript terminology as such, and not
                          > really different form borrowing "HashTable" from Java to describe the
                          > concept. It suffers as terminology because it encourages people to use
                          > Array objects for its implementation (which works because of the
                          > objectness of Arrays) when the behaviour of Object objects is enough for
                          > the task.
                          >
                          > In many cases the initial definition of such an object would be better
                          > achieved with an object literal:-
                          >
                          > var token = {
                          > key_phrase_star t:"This is a key phrase to use on screen",
                          > key_phrase_end: ", and here is another one."
                          > };[/color]

                          ....which is almost identical to the way I'm now doing it.
                          [color=blue][color=green]
                          >>[I'm doing this because I fully expect that, once the
                          >>application is released, translations for other languages
                          >>will become a priority requirement.][/color]
                          >
                          > Language negotiation is within the capabilities of the server and a task
                          > that probably should be done there.[/color]

                          Indeed, but I'm doing it client-side as a proof of concept. Once the
                          application I'm developing has a real home at work (instead of just my
                          work PC and my home PC), I'll be able to start doing more work server-side.
                          [color=blue]
                          > If the values in - token - are always non-empty strings then you will
                          > probably achieve another performance improvement changing the - typeof -
                          > test, with its string comparison operation, replacing it with a
                          > type-converting test:-
                          >
                          > if(token[nameX]){
                          > ...
                          > }[/color]

                          If token[nameX] doesn't exist (which should never happen), then it'll
                          work but will show up as a Javascript warning in Mozilla; unacceptable
                          as far as I'm concerned. Mind you, if I can guarantee that token[nameX]
                          is always present there's no need to test for it in the first place ;-)

                          Ian

                          Comment

                          • Richard Cornford

                            #14
                            Re: optimizing code...

                            "Ian Richardson" <zathras@chaos. org.uk> wrote in message
                            news:c17ll2$1eh 9k9$1@ID-99375.news.uni-berlin.de...
                            <snip>[color=blue][color=green]
                            >> if(token[nameX]){
                            >> ...
                            >> }[/color]
                            >
                            >If token[nameX] doesn't exist (which should never happen), then
                            >it'll work but will show up as a Javascript warning in Mozilla;
                            >unacceptable as far as I'm concerned. Mind you, if I can guarantee
                            >that token[nameX] is always present there's no need to test for it
                            >in the first place ;-)[/color]

                            If Mozilla have decided to generate a warning on type-converting tests
                            of undefined properties then whoever made that decision is an idiot. It
                            is completely acceptable and legal by ECMA 262 and a necessary (even
                            fundamental) practice in all cross-browser scripting.

                            Richard.


                            Comment

                            • Thomas 'PointedEars' Lahn

                              #15
                              Re: optimizing code...

                              Richard Cornford wrote:
                              [color=blue]
                              > "Ian Richardson" <zathras@chaos. org.uk> wrote [...][color=green]
                              >>if(typeof token[nameX] != "undefined" ) etc...
                              >>
                              >>Result: HUGE speed improvement!
                              >>
                              >>I like typeof, and there's no problem for me using it
                              >>given the target range of browsers I'm aiming at.[/color]
                              >
                              > If the values in - token - are always non-empty strings then you will
                              > probably achieve another performance improvement changing the - typeof -
                              > test, with its string comparison operation, replacing it with a
                              > type-converting test:-
                              >
                              > if(token[nameX]){
                              > ...
                              > }
                              >
                              > - The - if - test must resolve its expression to a boolean value, which
                              > it will do by internally type-converting the value of - token[nameX] -
                              > to boolean. Non-empty strings type-convert to boolean true while
                              > undefined values type-convert to boolean false.[/color]

                              It is to be noted that it needs to be distinguished between a
                              property of type "undefined" with its sole value `undefined',
                              and an undefined property. Using the above test will trigger
                              a warning in the latter case, even an error if "token" was not
                              declared, while using the "typeof" operator will not in either
                              case (and misses backwards compatibility only before NN3).

                              So think twice before you use short and simple "if" statements
                              in favor of those longer ones using the "typeof" operator.


                              PointedEars

                              Comment

                              Working...