I would like to know which situation has more “overhead”:
1) Case 1: 5 million objects sharing 30 functions. everytime a function is called, there is an overhead because it is necessary to do f.call(instance, arg1, arg2, etc)
//example code
function makeObject()
{
return { method1:func1,
method2:func2,
...
method30:func30 };
}
2) Case 2: 5 million objects with 30 functions each (= 150 million individual function instances). Everytime a function is called, there’s no “routing-overhead” but of course at the sacrifice of having more instances
//example code
function makeObject()
{
return { method1:func1.bind(asd),
method2:func2.bind(asd),
...
method30:func30.bind(asd) };
}
5 million is just a number my fingers typed out while my brain is still figuring out a nice number for an example.
Basically I want to know generally should we share functions whenever possible or create new ones?
(You can assume that i will never use the eval function anywhere in the entire page)
Since almost all modern browsers optimize the
prototype-andscopeschainlookup, you definitely should go for the sharing of methods.The optimization technique described in simple words, is a kind of
hash lookup tablewhich the javascript engine uses to access propertys/methods fromout of scopevariables. So there is very little overhead in comparision to a classicscope chain lookupwhere the engine has to crawl through each parent scopes variable-/activation object.This optimized
lookupwill only fail, if there is some kind of directeval‘ed code. Since anevalcan change the propertys from a context, an engine must fallback to a classic lookup algorythm (which is kind of slow).However, 5m objects are kind of unreal for Javascript-engines and I hope that those numbers are just examples. In a real world scenario, 5m objects calling
nnumber of functions would create a stack overflow and “too long running script” errors everywhere around.Alone the
parsing timefor 150 million functions will be disgraceful.