RainingChain
RainingChain

Reputation: 7746

Memory Size: What's Smallest Between String or Array

    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.

Upvotes: 2

Views: 249

Answers (3)

GameAlchemist
GameAlchemist

Reputation: 19294

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

Upvotes: 0

newfurniturey
newfurniturey

Reputation: 38446

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

Upvotes: 4

Xavier J
Xavier J

Reputation: 4668

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.

Upvotes: -1

Related Questions