Can/Does V8 use the same function code for multiple Function objects?

300 views
Skip to first unread message

T.J. Crowder

unread,
Dec 11, 2011, 9:10:00 AM12/11/11
to v8-users
Hi all,

Probably an easy question for anyone who's gotten into the internals
of V8 to answer: Can/Does V8 use the same function code for multiple
Function objects?

For example, consider:

* * * *
// Constructor function creating Thingy objects
function Thing() {
var privateData, morePrivateData;

this.doSomething = doSomething;

function doSomething() {
// Lots of code here, presumably using privateData and
morePrivateData
}
}
* * * *

Now suppose I create 1,000 `Thingy` objects via `new Thingy()` 1,000
times. Naturally, that will involve creating 1,000 `doSomething`
Function objects (you never know, I might do `this.doSomething.foo =
"bar";`, so the Function objects *must* be different), each with its
link back to the execution context in which it was created, etc.

But does V8 reuse the *code* of the `doSomething` function across
those 1,000 Function objects? Just setting up the context before
jumping into it? Or is all the code related to `doSomething`
duplicated in memory 1,000 times? (Which would seem un-V8-like. :-) )

I could try to establish this empirically, by creating a bunch of
`Thingy` objects with big `doSomething` functions and seeing how much
memory is used vs. creating a bunch of `Thingy` objects with very
small `doSomething` functions, but I'd prefer not to infer it if
someone happens to know off-hand.

Thanks in advance,
--
T.J. Crowder
Independent Software Engineer
tj / crowder software / com
www / crowder software / com

Kevin Millikin

unread,
Dec 12, 2011, 3:44:50 AM12/12/11
to v8-u...@googlegroups.com
Yes, the code is normally shared.

regards, Kevin

T.J. Crowder

unread,
Dec 19, 2011, 4:10:27 AM12/19/11
to v8-users
Thanks Kevin! Useful to know. Do you happen to have any idea whether
any of the other engines do this as well? I only ask because sometimes
when you're deeply involved in building something like this, you end
up knowing a fair bit about how the other guy does it... :-)

(Sorry for the late reply, I asked GGroups to notify me of replies,
and it still shows that it will, it just...didn't. Odd.)

Best,

-- T.J.

Kevin Millikin

unread,
Dec 19, 2011, 6:11:35 AM12/19/11
to v8-u...@googlegroups.com
Hi T.J.,

I don't really know for sure what any other JS engine does, but I would be quite surprised if they duplicated code for distinct function objects created from the same site in the source text.

T.J. Crowder

unread,
Dec 19, 2011, 6:30:53 AM12/19/11
to v8-users
Thanks again Kevin. I'm not so sure I'd be surprised if the old
JScript in IE8 and earlier duplicated them. :-) I may build a test
case to find out.

But good to know about V8.

Cheers,

-- T.J.

Reply all
Reply to author
Forward
0 new messages