Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Boolean::New() return a Handle<> while other primitives return Local<>?

These are the functions to create new primitives in the V8 C++ API:

Handle<Boolean> v8::Boolean::New(bool value)
Local<Number> v8::Number::New(double value)
Local<String> v8::String::New(const char *data, int length=-1)

I wonder why Boolean returns a Handle while the others return a Local.

My assumption is that it's related to booleans having only two possibly values but unfortunately the docs are really poor and do not mention things like that.

like image 799
ThiefMaster Avatar asked Sep 01 '12 16:09

ThiefMaster


1 Answers

This is the implementation of Boolean::New: (v8.h)

Handle<Boolean> Boolean::New(bool value) {
  return value ? True() : False();
}

And here is what we can get from api.cc:

v8::Handle<Boolean> True() {
  i::Isolate* isolate = i::Isolate::Current();
  if (!EnsureInitializedForIsolate(isolate, "v8::True()")) {
    return v8::Handle<Boolean>();
  }
  return v8::Handle<Boolean>(
      ToApi<Boolean>(isolate->factory()->true_value()));
}

Which looks like they are interning the true and false values for each Isolate. AFAIK this is an often used technique in virtual machines to decrease the number of created objects - for example, Java interns all string literals, as well as boolean and byte objects (even though interning is only mentioned for string in the JVM spec, I've also seen it happen for small integers, etc.).

like image 190
Ivan Vergiliev Avatar answered Oct 24 '22 22:10

Ivan Vergiliev