Memory overhead of typed arrays vs strings

前端 未结 2 696
南方客
南方客 2020-12-24 13:52

I am trying to reduce the memory usage of a javascript web application that stores a lot of information in memory in the form of a large number of small strings. When I chan

2条回答
  •  悲&欢浪女
    2020-12-24 14:34

    The typed arrays are not supposed to be used that way.

    If you want high memory efficiency, use just one typed array to hold all of your integer numbers. Instead of use a huge number of arrays to hold your integer numbers due to low level reasons.

    Those low level reasons are related to how much overhead is need to hold one object in memory, and that quantity depends on a few aspects like immutability and garbage collection. In this case hold one typed array has higher overhead than hold one simple string. Thats why you should pay that price one time only

    You should take advantage of:

    var a = [];                       for (let i=0; i<1000000; i++) a.push("1");
    var b = new Uint8Array(10000000); for (let i=0; i<1000000; i++) a[i] = 1;
    // 'b' is more memory efficient than 'a', just pay the price of Uint8Array one time
    // and save the wasted memory in string allocation overhead 
    

提交回复
热议问题