• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# JSVM Tuning Practices
2
3## JSVM Call Invocation
4
5The process of executing JavaScript (JS) code on a JavaScript virtual machine (JSVM) can be divided into the following layers:
6
7- Native: logic layer for the application to run JS code. In this layer, the APIs provided by the JSVM are used to compile and run JS code and create a code cache.
8- JSVM-API: intermediate layer between C/C++ and V8 JS engine. This layer ensures compatibility with JS engines of different versions and provides standardized practices of JS engines.
9- JSVM: JS engine layer, in which JS code is compiled and executed.
10
11If the application startup is slowed down due to unnecessary overheads generated by using of the JSVM, you can analyze the cause and make optimization in the three layers.
12
13## Accelerating Startup
14
15For the applications that use JSVM, optimization can be made in the cold startup and hot startup.
16In the cold startup, generally, the initial startup, there is no profile or cache that can be used for optimization.
17In the hot startup, the code cache can be used for optimization.
18
19### Reducing Overheads of the JSVM Layer
20
21Some of the overheads in the JSVM layer are generated from compilation. You can adjust the options passed in when JSVM-API is called to reduce the compilation overhead of the JS engine in the main thread.
22In the following example, the **eagerCompile** parameter specifies the compilation behavior. You can enable this option in the startup scenarios to optimize the compilation effect.
23
24```cpp
25/**
26 * ...
27 * @param eagerCompile: Whether to compile the script eagerly.
28 * ...
29 */
30JSVM_EXTERN JSVM_Status OH_JSVM_CompileScript(JSVM_Env env,
31                                              JSVM_Value script,
32                                              const uint8_t* cachedData,
33                                              size_t cacheDataLength,
34                                              bool eagerCompile, // Set it to true to enable full compilation.
35                                              bool* cacheRejected,
36                                              JSVM_Script* result);
37```
38
39Using a code cache also helps speed up compilation. For details, see [Accelerating Compilation Using a Code Cache](use-jsvm-about-code-cache.md).
40
41#### Hot Startup: Creating a Code Cache with Adequate Code
42
43To speed up hot startup, create a code cache with adequate code to reduce the compilation overhead. The code coverage of the created code cache determines the optimization effect of the hot startup.
44
45To create a code cache with adequate code, set **eagerCompile** to **true** for the compilation before the code cache is created. In this way, full compilation is performed in V8, which ensures high code coverage of the cache.
46
47This approach, however, causes extra compilation time, which may increase the cold startup time used. Read on to learn the ways to optimize the cold startup in the native layer.
48
49#### Cold Startup: Disabling eagerCompile
50
51Enabling **eagerCompile** increases the compilation time for cold startup. To reduce the compilation time, you can use V8 lazy compile, which delays the compilation of JS code until it is executed.
52
53By disabling **eagerCompile** for the code that may block the main thread, you can speed up the code startup.
54
55### Reducing Time Overheads in the Native Layer
56#### Reducing the Code Cache Impact in Cold Startup
57
58It seems contradictory since you are advised to enable **eagerCompile** for higher hot startup performance and to disable **eagerCompile** for higher cold startup performance. To avoid the trade-off between cold startup and hot startup performance, let's focus on the code cache itself.
59
60Code compilation is required before a code cache is created, and the creation of the code cache generates overheads.
61
62To use a code cache without compromising the cold startup speed in the native layer, you can start another thread to create the code cache.
63
64You can use either of the following methods to achieve this purpose:
65
66- Start another thread to complete the code compilation and create a code cache. In this way, you can enable **eagerCompile** for code cache creation and disable it for cold startup. This approach decouples the code cache creation and the application running, and you do not need to consider the time when the code cache is created. However, the peak resource usage during the application running may increase. The pseudo-code of this process is as follows:
67
68```
69async_create_code_cache() {
70  compile_with_eager_compile();
71  create_code_cache();
72  save_code_cache();
73}
74
75...
76
77if (has_code_cache) {
78  evaluate_script_with_code_cache();
79} else {
80  start_thread(async_create_code_cache());
81  evaluate_script_without_code_cache();
82}
83```
84
85
86- After all the paths are executed in the startup, start a new thread to create a code cache. In this way, you can create a cache with sufficient code without enabling **eagerCompile** while maintaining the hot startup performance. This approach will not increase the peak resource usage or affect the I/O. However, the time for generating the code cache is restricted. The pseudo-code of this process is as follows:
87
88```
89async_create_code_cache() {
90  compile_with_out_eager_compile();
91  create_code_cache();
92  save_code_cache();
93}
94
95...
96
97if (has_code_cache) {
98  evaluate_script_with_code_cache();
99} else {
100  evaluate_script_without_code_cache();
101}
102
103...
104
105if (script_run_completed) {
106  start_thread(async_create_code_cache());
107}
108```
109
110
111### Using Performant JSVM-API
112
113You can use more performant APIs provided by JSVM-API to improve performance.
114
115#### Using IsXXX Instead of TypeOf
116
117To determine the native type of an object, it is inefficient to use **OH_JSVM_TypeOf** to obtain the object type and check whether the object type is the same as a specific type. Instead, you can use the **Is**XXX APIs.
118
119- Example (not recommended):
120
121
122```cpp
123bool Test::IsFunction() const {
124    HandleScopeInit(*env);
125    JSVM_Value jsvmValue;
126    ObjectWrappingGet(*env, jsvmRef, jsvmValue);
127    // Type judgment starts.
128    bool result;
129    JSVM_ValueType valueType;
130    OH_JSVM_TypeOf(*env, jsvmValue, &valueType);
131    OH_JSVM_CloseHandleScope(*env, scope);
132    // Type judgment ends.
133    return valueType == JSVM_FUNCTION;
134}
135```
136
137- Example (recommended):
138
139
140```cpp
141bool Test::IsFunction() const {
142    HandleScopeInit(*env);
143    JSVM_Value jsvmValue;
144    ObjectWrappingGet(*env, jsvmRef, jsvmValue);
145    // Type judgment starts.
146    bool result = false;
147    OH_JSVM_IsFunction(*env, jsvmValue, &result); // Check whether the object type is function.
148    OH_JSVM_CloseHandleScope(*env, scope);
149    // Type judgment ends.
150    return result;
151}
152```
153
154The following optimization decreases the code execution time by 150 ms, accounting for about 5% of the performance benefits of an applet.
155
156#### Using OH_JSVM_CreateReference to Avoid Creating Redundant Objects
157
158Generally, the procedure for creating a reference to an object is as follows:
159
160Create an object -> Set a value of the object -> Create the reference to the object
161
162If the object already has the value, you can directly create a reference to the value.
163
164- Example (not recommended):
165
166```cpp
167// (1) Open a handle scope.
168JSVM_HandleScope scope;
169OH_JSVM_OpenHandleScope(*env, &scope);
170// (2) Obtain JSVM_Value.
171JSVM_Value jsvmValue;
172OH_JSVM_GetNull(*env, &jsvmValue);
173// (3) Create a Reference for JSVM_Value and save it.
174JSVM_Value wrappingObject;
175OH_JSVM_CreateObject(*env, &wrappingObject);
176OH_JSVM_SetElement(*env, wrappingObject, 1, jsvmValue);
177OH_JSVM_CreateReference(*env, wrappingObject, 1, &result->p_member->jsvmRef);
178// (4) Close the handle scope.
179OH_JSVM_CloseHandleScope(*env, scope);
180```
181
182- Example (recommended):
183
184```cpp
185// (1) Open a handle scope.
186JSVM_HandleScope scope;
187OH_JSVM_OpenHandleScope(*env, &scope);
188// (2) Obtain JSVM_Value.
189JSVM_Value jsvmValue;
190OH_JSVM_GetNull(*env, &jsvmValue);
191// (3) Create a Reference for JSVM_Value and save it.
192OH_JSVM_CreateReference(*env, jsvmValue, 1, &result->p_member->jsvmRef); // Create a reference to an object of any type, making your code simpler and more performant.
193// (4) Close the handle scope.
194OH_JSVM_CloseHandleScope(*env, scope);
195```
196
197This optimization also helps reduce the number of API calls for another applet and decreases the code execution time by 100+ ms, accounting for about 3% of the performance benefits.
198