chakra-core / chakra-core/ChakraCore
Reuse of pid hashtable of parser for DynamicFunction
- Dominant language
- JavaScript
- Stars
- 9.3k
- Forks
- 1.2k
- PR merge metrics
- No merged PRs in 30d
Description
```js
// Dynamic functions
var x = "function(a, b, c) { console.log('hello'); }";
var func = new Function(x);
```
Today, for above code, we [create a pid hash table](https://github.com/Microsoft/ChakraCore/blob/master/lib/Parser/Parse.cpp#L11287-L11289) while validating syntax for formals (`(a,b,c)`) and for function body (`return a+b+c;`) [here](https://github.com/Microsoft/ChakraCore/blob/master/lib/Runtime/Library/JavascriptFunction.cpp#L217-L229). Finally we do the actual parsing of dynamic function (`function anonymous(a,b,c ) {return a+b+c; }`) and generate bytecode. We can avoid creating separate hash table for each validation/parsing and just have single instance of Parser doing these validation and parsing. With that we can save 50% of allocation / free of CRT heap. Below ETW profile shows the impacting size for creating these hash tables by `ValidateSyntax` method. As seen below, if we just have 1 hash table for parsing and validating formals , function body, we can reduce memory allocation/freeing by 50%. So it should give some speed-up because of less malloc/free calls.

Above screen shot doesn't show impacting size for actual entries that are inserted in hash table. Once we share hash tables, we will also avoid allocation for these entries repeatedly.
Other scenarios for which similar code path is hit are:
```js
// async functions
var AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;
var af = new AsyncFunction('return await Promise.resolve(0);');
// generator function
var GeneratorFunction = Object.getPrototypeOf(function* () { }).constructor;
var gf = new GeneratorFunction('yield 1; return 0;');
```
Contributor guide
Assessment
This issue has not been assessed yet.