Fast way to iterate through an object's properties?

708 views
Skip to first unread message

Dave Galbraith

unread,
Jul 5, 2015, 10:49:11 PM7/5/15
to v8-u...@googlegroups.com
I have code in Javascript that sends an object to my node v8 C++ add-on module. I want to iterate through the keys and values of that object in C++. Currently I do this:

    Local<Object> pt = args[0].As<Object>();

    v8::Local<v8::Array> keys = pt->GetOwnPropertyNames();
    uint32_t length = keys->Length();
    for (u_int32_t i = 0; i < length; ++i) {
        v8::Local<v8::Value> key = keys->Get(i);
        v8::Local<v8::String> key_str(key->ToString());
        v8::String::Utf8Value tag(key_str);
        v8::String::Utf8Value val(pt->Get(key_str));
    // do stuff with tag and val
    .......

The calls to keys->Get() and pt->Get() are so, so, so slow: profiling reveals that just those two lines take 70% of the runtime of my application. Is there a better way to do this? My searching came up with GetIndexedPropertiesExternalArrayData, but apparently that's gone now.

Ben Noordhuis

unread,
Jul 6, 2015, 8:05:59 AM7/6/15
to v8-u...@googlegroups.com
External array data has been replaced with array buffers and typed
arrays. You can't use them if the properties are strings, though.

If the v8::Object::Get() calls are the slow part, you can iterate over
them in JS land and call C++ for individual key / value pairs: for
(var key in obj) binding.process(obj, key, obj[key]);

for/in doesn't get optimized at the moment so you may want to use
Object.keys() or Object.getOwnPropertyNames() instead.

v8::Object::GetOwnPropertyNames() doesn't do the same thing as
Object.getOwnPropertyNames(), by the way, it's closer to
Object.keys(). See https://code.google.com/p/v8/issues/detail?id=3861
for more details.
Reply all
Reply to author
Forward
0 new messages