skip to Main Content

Is there any fast way to reduce the bytes of objects?

I send the objects from a server to the browser, and it’s taking up quite a lot of bandwidth

My objects look like this, but with more properties:

{
  1: {width: 10.25, height: 30.75,},
  2: {width: 7.5, height: 1.25,},
}

2

Answers


  1. Your problem has a ton of solutions.
    I will share some of the most common ways of network optimization.

    1. Strip down the object before serialization. Consider only the properties which are of importance to the communication in question.
    2. Consider other serialization options. JSON encoding is just one option for encoding data sent over network. Other options such as binary serialization which is much more performant than text (here JSON). binary serialization.
    3. Other options you should consider include remote procedure calls which have been demonstrated to be more performant than REST.

    In the end, all these options need some sort of understanding to ensure getting the best results of each.

    Login or Signup to reply.
  2. Send your data as CSV, that way you don’t need to include field names into your payload in every item.

    If you want JSON anyway you could minify your object properties and send the minification map together with the data:

    const obj = {
        1: { width: 10.25, height: 30.75, },
        2: { width: 7.5, height: 1.25, },
    };
    
    let charCode = 97;
    
    const pack = obj => JSON.stringify(
        Object.entries(obj).reduce((packed, [idx, item]) => {
            packed.obj[idx] = Object.keys(item).reduce((obj, key) => {
                obj[packed.map[key] ??= String.fromCharCode(charCode++)] = item[key];
                return obj;
            }, {});
            return packed;
        }, { obj: {}, map: {} })
    );
    
    const unpack = str => {
    
        const { obj, map } = JSON.parse(str);
    
        const inverted = Object.entries(map).reduce((inverted, [k, v]) => {
            inverted[v] = k;
            return inverted;
        }, {});
    
    
        return Object.entries(obj).reduce((obj, [idx, item]) => {
            obj[idx] = Object.entries(item).reduce((item, [key, val]) => {
                item[inverted[key]] = val;
                return item;
            }, {});
            return obj;
        }, {});
    
    };
    
    const packed = pack(obj);
    console.log('PACKED:', packed);
    const unpacked = unpack(packed);
    console.log('UNPACKED', JSON.stringify(unpacked));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search