Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign and immediately delete property

Tags:

javascript

I am no javascript programmer and am totally puzzled by what this code does and what it is used for:

function map(x) {
    x = Object.create(null);
    x.x = 0;
    delete x.x;
    return x;
}

It's part of what you get when using the dart2js compiler.

I'm not trying to understand the whole context, but what does assigning a property and deleting it directly again help achieve?

This looks like outsmarting some internal JS engine behaviour.

EDIT: As requested, here's the complete out.js as generated by dart2js (input is the "Hello world!" example from Wikipedia): https://gist.github.com/Blutkoete/59be155b2642832e9acd383df0857d02

EDIT 2: gurvinder372's link indicates is has to do with "delegating to anonymous JS objects for performance", but I'll probably need a lot of experience with JS to understand that.

like image 553
Blutkoete Avatar asked Apr 17 '18 10:04

Blutkoete


1 Answers

Well... This is an interesting topic and understanding this trick takes to read a little bit on the object representation of V8 compiler. I am not an expert on this but the topic was interesting enough to intrigue me to search for some answer. So here is what i have found.

First of all deleting a property seems to be a trick to change the internal structure of how object properties are kept and accessed. In other words deleting a property switches the object to dictionary mode where the properties are kept in a hash map. So when a dummy property is deleted immediately after it's created gives you an object in dictionary mode.

V8 can handle minor divergences like this just fine, but if your code assigns all sorts of random properties to objects from the same constructor in no particular order, or if you delete properties, V8 will drop the object into dictionary mode, where properties are stored in a hash table. This prevents an absurd number of maps from being allocated.

Taken from this nice article A tour of V8: object representation

like image 60
Redu Avatar answered Nov 15 '22 15:11

Redu