www.webdeveloper.com
Results 1 to 9 of 9

Thread: arrays vs types

  1. #1
    Join Date
    Nov 2010
    Posts
    4

    arrays vs types

    Just wondering which of these is more resource-efficient way to do stuff...

    Example 1:

    var itemName=["triangle","square","circle"];
    var itemSides=[3,4,0];
    var itemColor=["Red","Green","Blue"];


    Example 2:

    var itemTriangle={};
    itemTriangle.sides=3;
    itemTriangle.color="Red";

    var itemSquare={};
    itemSquare.sides=4;
    itemSquare.color="Green";

    var itemCircle = {};
    itemCircle.sides=0;
    itemCircle.color="Blue";

  2. #2
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    It is rather a matter of human reading easiness than a matter of resources efficiency. And it depends on what you want to do further. In your first example, you are dealing with Arrays, while in your second you have some Objects.

    I might give you a third way, on using a constructor to create some Objects:
    Code:
    <script type="text/javascript">
    function Constructor(sides,color){
    this.sides=sides;
    this.color=color;
    }
    var itemTriangle=new Constructor(3,'Red');
    var itemSquare=new Constructor(4,'Green');
    var itemCircle=new Constructor(0,'Blue');
    </script>

  3. #3
    Join Date
    Mar 2010
    Location
    Singapore
    Posts
    367
    Quote Originally Posted by Kor View Post
    I might give you a third way, on using a constructor to create some Objects:
    Code:
    <script type="text/javascript">
    function Constructor(sides,color){
    this.sides=sides;
    this.color=color;
    }
    var itemTriangle=new Constructor(3,'Red');
    var itemSquare=new Constructor(4,'Green');
    var itemCircle=new Constructor(0,'Blue');
    </script>
    Above is known as Constructor functions and most ppl are familiar due to OO from say C++ and Java.

    Recently I explore some more on OO Javascript and it seems Javascript offer a few other ways to construct an object. One way is object copy from object.

    E.g
    Code:
    function copyFrom(src) {
      var dest = {};
      for(var i in src) {
        dest[i] = src[i];
      }
      return dest;
    };
    
    var parent = {
      test:1,
      test2:2
    };
    
    var child = copyFrom(parent);
    
    console.log(child.test);
    console.log(child.test2);
    Or from Douglas Crockford.

    function extends(child, parent) {
    child.prototype = parent.prototype; // this chain the child to the parent prototype
    child.prototype.constructor = child;
    return child;
    }

    There are variations of the above 2 new ways I learnt so it seems Javascript prototype model can be very confusing.

    I guess for ppl, new <something>(); is the most intuitive but this is NOT the only way we can construct objects in Javascript.

    PS Above code snippet not tested so please correct me.
    Last edited by sohguanh; 11-22-2010 at 03:42 AM.

  4. #4
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Quote Originally Posted by sohguanh View Post
    I guess for ppl, new <something>(); is the most intuitive but this is NOT the only way we can construct objects in Javascript
    I didn't say that using a constructor is the only way. But the prototype method does not create objects, it uses the prototype (let's say a sort of clone) of the object and it appends new properties to the prototype, not to the object itself. As a result, yes, you may say that the new properties are applied upon all the instances of that object. Sort of... because this would not be a precise description.

    JavaScript has no classes, nor instances (as a matter of fact it makes no difference between objects, classes and instances) - for JavaScript everything is an object. And JavaScript uses the delegation (from object to its prototype), not the inheritance.

    Unlike C++ and Java, JavaScript is a prototype based language, not a class based one.

    And relative to the nevart question, using the prototype method could be a little much to intricate solution, as nevart wants to create new objects and and give them properties at the same time. The prototype method is to be applied upon an already/previously created/existent object.

  5. #5
    Join Date
    Dec 2009
    Location
    Shropshire UK
    Posts
    152
    @sohguanh,

    The first example you gave there is a shallow copy. You maybe also want to add the hasOwnProperty method as follows. That way you're only copying the object's own properties rather than properties from the prototype as well.

    PHP Code:
    function copyFrom(src) {
      var 
    dest = {};
      for(var 
    i in src) {
        if (
    src.hasOwnProperty(i)){
          
    dest[i] = src[i];
        }
      }
      return 
    dest;
    }; 
    Where the shallow copy fails though is if your object's properties are of a reference type like arrays for instance.

    e.g.
    PHP Code:
    var parent = {
      
    test:[1,2,3],
      
    test2:['apple','banana','grapes']
    };

    var 
    child copyFrom(parent);

    console.log(parent.test2);// 'apple','banana','grapes'
    console.log(child.test2);// 'apple','banana','grapes'

    child.test2.push('strawberry'); // both object instances reference the same array
    console.log(parent.test2);// 'apple','banana','grapes','strawberry'
    console.log(child.test2);// 'apple','banana','grapes'.'strawberry' 
    RLM

  6. #6
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    See http://www.svidgen.com/images/Array%...Benchmarks.pdf

    The benchmark is somewhat limited. It only tests array instantiation -- not any actual property assignments. And it doesn't test object instantiation. But, it's reasonable to assume that a similar difference in efficiency exists for objects and assigning values. (I could expand on these benchmarks if anyone is interested.)

    So, the most computationally efficient is probably the literal syntax. This ...
    HTML Code:
    var obj = {'key':'value'};
    .. is more efficient than this ..
    HTML Code:
    var obj = new Object();
    obj.key = 'value';
    However, unless you're doing this sort of thing iteratively, hundreds of thousands of times, particularly in response to "navigational" input, the gain is going to be negligible. And with a new JavaScript engine coming out (or having just come out?) for FF, the nearly 50% efficiency difference may be significantly less drastic.

    Though, it's worth mentioning that the biggest efficiency concern for most web applications is transfer time. The literal notations (JSON) are going to be fairly beneficial in that respect. And the differences there can be fairly easily measured by simply comparing file sizes with one notation versus the other.

    Taking the very simple example above, not including the final newlines, the difference is between 26 and 42 characters, a potential savings of 62% in file/transfer size, and potentially zipping/unzipping time. Extrapolating that percentage to real-life-sized javascript, that ends up being very good for response time -- and therefore good for the user experience, hardware and bandwidth costs, and the overall load-bearing potential of your server(s).

    Overall, JSON is probably better. However, if you're not dealing with a high profile application, highly complex client-side operations, a significant amount of potential saving on file and transfer size, or an already-swamped server, it probably doesn't matter a great deal. You're mostly OK doing whatever looks better to you [and your collaborators].

    To reiterate, the biggest concern for a site of any size will usually be that transfer overhead: if you can take a collection of javascripts down 60, 40, or even 20%, your page will feel snappier on the initial load, and it could suddenly become a more feasible experience for people stuck on dialup or heavily saturated, shared connections.
    Jon Wire

    thepointless.com | rounded corner generator

    I agree with Apple. Flash is just terrible.

    Use CODE tags!

  7. #7
    Join Date
    Nov 2010
    Posts
    4
    Hey guys... thanks for all the info and ideas. Seems to be an unexpectedly controversial topic. I wasn't really confident that there would be any gains, but I had hoped for the possibility. Without support for data types, it appears that arrays can very quickly cause meltdowns on systems that don't have a lot of memory available.

  8. #8
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Quote Originally Posted by nevart View Post
    Without support for data types, it appears that arrays can very quickly cause meltdowns on systems that don't have a lot of memory available.
    Who said so?

    First, let's make the terms clear. In javascript the custom data structures are of two kinds:

    1. Arrays (vectors, lists, or sequences). Arrays are ordered list of values.
    Code:
    var myArray=[
    'red',
    'green',
    'blue'
    ]
    2. Objects (records, structs, dictionaries, hash tables, keyed lists, or associative arrays). Objects are unordered collections of pairs property:value
    Code:
    var myObject={
    'tomato':'red',
    'apple':'green',
    'sky':'blue'
    }
    The utilization of one or another is dictated only by the purpose of the construction. Sometimes it is better to create arrays (for instance if you have a simple list of values), sometimes it is better to use objects (if you need to have pairs of property:value attached to that object).

    The "memory availability" has nothing to do here. After all, both structure have keys, arrays - an implicit ordered index, starting from 0, the objects have their properties as keys. It is true that an integer will occupy less memory than a string, but unless we are talking about hundreds and hundreds of elements, the difference in the allocated memory is insignificant.
    Last edited by Kor; 11-23-2010 at 08:35 AM.

  9. #9
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    Quote Originally Posted by nevart View Post
    Hey guys... thanks for all the info and ideas. Seems to be an unexpectedly controversial topic. I wasn't really confident that there would be any gains, but I had hoped for the possibility. Without support for data types, it appears that arrays can very quickly cause meltdowns on systems that don't have a lot of memory available.
    Ok ... so we're talking strictly about memory utilization? This typically isn't an issue for client-side web app development. But, for complex tasks, I could see it becoming an issue. So ...

    Any data structure that's instantiated N times will consume N * { sizeof(<type>) + sizeof(<index>) } space. Variables in the global space operate similarly to objects: the variable names are just keys/properties of the window object. All of the following lines take up space to index "something" in association with "else", and the last example takes up a little extra to index "obj" and provide an underlying structure to hold "something" :

    HTML Code:
    var something = "else";
    window["something"] = "else;
    var obj = {"something":"else"};
    In my rudimentary "benchmarks" I found that appending TRUE 1,000,000 times to an array named something increased memory utilization in Chrome on OS X by 7.8MB. Appending TRUE to window["something_" + index] 1,000,000 times increased memory utilization by about 105MB. With an average of about 15 characters per index * 1,000,000 = 15MB of raw string data, we're either looking at some pretty significant overhead to index those keys, or we're looking at a LOT of copying as the window object expands. (consuming much more memory in any case)

    So, the question of whether it's more memory-efficient to use side-by-side arrays versus "objects" is fairly clear. Arrays will be smaller. For example, and again using Chrome on OS X, the following consumes about 13.2MB:

    HTML Code:
    var att_a = [];
    var att_b = [];
    for (i = 0; i < 1000000; i++) {
      att_a.push('a');
      att_b.push('b');
    }
    And the following consumes over twice as much -- about 30.3MB:
    HTML Code:
    var obj = [];
    for (i = 0; i < 1000000; i++) {
      obj.push({'att_a':'a','att_b':'b'});
    }
    So, if you're dealing with a LOT of objects with many attributes, you may at some point be forced to use the less convenient side-by-side array "structure." However, unless you're bumping up against memory limits for some seriously heavy computation, keep things organized in an easily manageable and safer manner.

    You can't accidentally mis-align the attributes across a set of objects like you can with independent arrays.


    ADDENDUM: All determinations about memory consumption were based on memory deltas, pre and post execution, according to Chrome's task manager. "Fresh" tabs were used for each test. Tests were performed using http://www.svidgen.com/javascript_benchmark
    Last edited by svidgen; 11-23-2010 at 09:48 AM.
    Jon Wire

    thepointless.com | rounded corner generator

    I agree with Apple. Flash is just terrible.

    Use CODE tags!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles