Rush W.
Rush W.

Reputation: 1361

Performance related issue for javascript object

I wanted to know if there is some performance issue related in the two below coding paradigms. Which one is the best and why?

var data = [{
        "name": "ABC",
        "code": 1,
        "age": 97
    },{
        "name": "XYZ",
        "code": 12,
        "age": 12
    },{
        "name": "LMN",
        "code": 121,
        "age": 172
    }
];

var response = [];

Method1

data.forEach(function(entry){
        var obj = {
            "NAME": entry["name"],
            "AGE": entry["age"]
        };
        response.push(obj);
});

Method2

data.forEach(function(entry){
        var obj = {};
        obj["NAME"] = entry["name"];
        obj["AGE"] = entry["age"];
        response.push(obj);
});

For output object, I need say suppose, only 10 keys out of 100 keys The object has many keys in it. Only limited are shown in the example. Which coding standard to choose and why? Please, can anybody explain?

Upvotes: 0

Views: 62

Answers (2)

rmn
rmn

Reputation: 1169

Both approaches are fine and one should not be "faster" than the other, at least not enough to justify using the other one. Use the one you like.

But, if you're still looking for closure. The first one should be faster since it defines the entire object all at one go. There's no "look-ups" the engine have to do. It's all done at one go.

On a separate note, consider using the dot notation, it should be faster since the engine will not have to create strings. So, change

entry["name"]

to

entry.name

Also, if this is your actual code and the purpose is to modify the result to have just name and age and no code. You can do

data.forEach(user => delete user.code)

Upvotes: 1

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

No need to create the objects and then make a Array.prototype.push() for everly loop iteration...

You can directly use Array.prototype.map() instead of Array.prototype.forEach() and better access the object property values by the dot notation:

const data = [{
    "name": "ABC",
    "code": 1,
    "age": 97
  },{
    "name": "XYZ",
    "code": 12,
    "age": 12
  },{
    "name": "LMN",
    "code": 121,
    "age": 172
  }
];

const response = data.map(obj => ({
  NAME: obj.name,
  AGE: obj.age
}));

console.log(response)

Upvotes: 2

Related Questions