2
    var string = '';
    var array = [];

    for(var i = 0; i < 10000; i++){
        string += '0';
        array.push(0);
    }

Which one would be smaller? When/where is the breakpoint between the two?

Note: The numbers are always 1 digit.

Creating the array is about 50% faster than creating the string.

RainingChain
  • 7,397
  • 10
  • 36
  • 68

3 Answers3

4

Based on the answer here, you can roughly calculate the size of different data-types in JavaScript.

The equations used, pertaining directly to your question, to calculate the size in bytes:

string = string.length * 2
number = 8

Based on this, the size of your array variable would depend on the content-type being placed in it. As you're inserting numeric values, each offset would be 8 bytes, so:

array[number] = array.length * 8

With these equations, the sizes are:

string = 20000
 array = 80000

If you were to use array.push('0') instead (i.e. use strings), the sizes of string and array should be roughly equal.

References:

  1. The String Type - EMCAScript Language Specification:

    The String type is the set of all finite ordered sequences of zero or more 16-bit unsigned integer values.

  2. The Number Type - EMCAScript Language Specification:

    The Number type has exactly 18437736874454810627 (that is, 264−253+3) values, representing the double-precision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic

Community
  • 1
  • 1
newfurniturey
  • 37,556
  • 9
  • 94
  • 102
  • Actually, a single large string should use much less memory than an array of single-character strings. – SLaks Jan 16 '14 at 18:54
0

To store small numbers in an array, best way is to use a Int8Array.
(https://developer.mozilla.org/en-US/docs/Web/API/Int8Array).

GameAlchemist
  • 18,995
  • 7
  • 36
  • 59
-1

The array will be faster always.

With the string, each time you append, the runtime has to allocate space for the new string, and then throw away the last version of the string.

With the array, it's just extending a linked list.

http://en.wikipedia.org/wiki/Linked_list

On the other hand, the string will probably consume less memory since all the data will be in a single contiguous block of RAM, whereas the array will have the data and all the linked-list pointers too.

Xavier J
  • 4,326
  • 1
  • 14
  • 25
  • 1
    I doubt that most Javascript implementations would use linked lists to implement arrays, because they need to provide index access, which would have linear complexity with a linked list. I would rather expect them to use a hash table or a binary tree. – Philipp Jan 16 '14 at 18:19
  • Yes, where is the evidence that an array is implemented using a linked-list? Sounds like a guess to me. – Lee Taylor Jan 16 '14 at 18:23
  • The specific implementation of the collection may differ, that's true. But in any case, adding to a collection is going to generally be faster than doing string appends. – Xavier J Jan 16 '14 at 18:29