• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Accelerating Compilation Using a Code Cache
2
3## Introduction to Code Cache
4
5JSVM-API provides APIs for creating a code cache and using the code cache to store and manage compiled code to accelerate compilation. The code cache stores the code that has been compiled into native code by the compiler. This helps speed up the execution by avoiding repeated compilation of the same code. The procedure for creating and using a code cache is as follows:
6
7- Use the **compile** APIs to obtain **JSVM_Script**.
8- Call **OH_JSVM_CreateCodeCache** with the passed-in **JSVM_Script** to create a code cache.
9- Save the created code cache. During the next compilation, pass the code cache as a parameter to the **compile** APIs.
10
11The compilation using the code cache greatly reduces the compilation time because the serialized script in the code cache only needs to be deserialized, eliminating the need for parsing and compiling the code. In this way, the compilation process is simplified as a process for reading data.
12
13## Code Cache Verification Specifications
14| Specification      | Description                                           |
15| ---------- | -------------------------------------------------- |
16| Integrity verification | Checks whether the actual length of the cache is the same as that when the cache is generated.                |
17| Compatibility verification | Checks whether the JSVM version and compilation options of the generated cache are the same as the current one.   |
18| Consistency verification | Checks whether the length of the JavaScript source code for generating the cache is the same as that of the current input source code. |
19
20## Example
21
22The following pseudocode demonstrates a typical use case. During the second compilation, if the value of **cacheRejected** is **true**, the code cache is rejected and cannot take effect, and the compilation time is not affected. If the value of **cacheRejected** is **false**, the compilation is greatly accelerated.
23
24For details about how to use the JSVM-API, see [JSVM-API Data Types and APIs](./jsvm-data-types-interfaces.md). The following example only demonstrates the call procedure.
25For details about the cross-language interaction, see [JSVM-API Development Process](./use-jsvm-process.md).
26
27```c++
28#include "napi/native_api.h"
29#include "ark_runtime/jsvm.h"
30#include <hilog/log.h>
31#include <string>
32
33JSVM_Value UseCodeCache(JSVM_Env env, JSVM_CallbackInfo info) {
34    // Set compilation parameters.
35    JSVM_Value jsSrc;
36    JSVM_Script script;
37    JSVM_Value result;
38    size_t length = 0;
39    const uint8_t* dataPtr = nullptr;
40    bool cacheRejected = true;
41    static std::string src = R"JS(
42        a = 65536;
43        b = 32768;
44        c = a + b;
45    )JS";
46
47    // Create a code cache.
48    {
49        JSVM_HandleScope handleScope;
50        OH_JSVM_OpenHandleScope(env, &handleScope);
51
52        // Convert the source code string into a JS string.
53        OH_JSVM_CreateStringUtf8(env, src.c_str(), src.size(), &jsSrc);
54
55        // Compile the JS code.
56        OH_JSVM_CompileScript(env, jsSrc, nullptr, 0, true, nullptr, &script);
57
58        // Run the JS code.
59        OH_JSVM_RunScript(env, script, &result);
60        int value = 0;
61        OH_JSVM_GetValueInt32(env, result, &value);
62        OH_LOG_INFO(LOG_APP, "first run result: %{public}d\n", value);
63
64        if (dataPtr == nullptr) {
65            // Save the script compiled from the JS source code to the cache to prevent repeated compilation and improve performance.
66            OH_JSVM_CreateCodeCache(env, script, &dataPtr, &length);
67        }
68
69        OH_JSVM_CloseHandleScope(env, handleScope);
70    }
71
72    // Use the code cache.
73    {
74        JSVM_HandleScope handleScope;
75        OH_JSVM_OpenHandleScope(env, &handleScope);
76
77        // Convert the source code string into a JS string.
78        OH_JSVM_CreateStringUtf8(env, src.c_str(), src.size(), &jsSrc);
79
80        // Use the code cache to compile the JS code.
81        OH_JSVM_CompileScript(env, jsSrc, dataPtr, length, true, &cacheRejected, &script);
82
83        // Run the JS code.
84        OH_JSVM_RunScript(env, script, &result);
85        int value = 0;
86        OH_JSVM_GetValueInt32(env, result, &value);
87        OH_LOG_INFO(LOG_APP, "second run result: %{public}d\n", value);
88
89        OH_JSVM_CloseHandleScope(env, handleScope);
90    }
91    OH_LOG_INFO(LOG_APP, "cache rejected: %{public}d\n", cacheRejected);
92    return result;
93}
94
95// Register a callback.
96static JSVM_CallbackStruct param[] = {
97    {.data = nullptr, .callback = UseCodeCache}
98};
99static JSVM_CallbackStruct *method = param;
100// Register the C++ callback as a JSVM globalThis.UseCodeCache property for the JS to call.
101static JSVM_PropertyDescriptor descriptor[] = {
102    {"UseCodeCache", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
103};
104
105// Call C++ code from JS.
106const char* srcCallNative = R"JS(globalThis.UseCodeCache())JS";
107```
108
109**Expected Result**
110```
111first run result: 98304
112second run result: 98304
113cache rejected: 0
114```
115
116## Precautions
117
118In the preceding code, a code cache is used for compilation. In **OH_JSVM_CompileScript(env, jsSrc, dataPtr, length, true, &cacheRejected, &script)**, the **cacheRejected** parameter is passed in to obtain whether the code cache is rejected in the compilation process. This status includes several situations:
119
120- Code cache verification failed
121- Code cache verification successful
122- The code cache is not verified because there is a compilation cache in the memory
123
124**cacheRejected** will be set to **true** in the first case and to **false** in the latter two cases. Therefore, it is important to note that event if **cacheRejected** is **false**, it does not necessarily mean that the code cache is used.
125