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 process is as follows:
6
71. Use the **compile** APIs to obtain **JSVM_Script**.
82. Call **OH_JSVM_CreateCodeCache** with the passed-in **JSVM_Script** to create a code cache.
93. 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## Example
14
15The following pseudocode demonstrates a typical use case. During the second compilation, if the value of **cacheRejected** is not **true**, the code cache is successfully used and the compilation is greatly accelerated.
16
17The following example provides only the APIs used in the process. For details about JSVM-API, see [JSVM](../reference/common/_j_s_v_m.md).
18
19```c++
20
21JSVM_Env env;
22
23...
24
25using namespace std;
26static string src = R"JS(
27const concat = (...args) => args.reduce((a, b) => a + b);
28throw new Error("exception triggered")
29)JS";
30
31// Set compilation parameters.
32JSVM_Value jsSrc;
33JSVM_Script script;
34size_t length = 0;
35const uint8_t* dataPtr = nullptr,
36bool cacheRejected = false;
37
38// Create a code cache.
39{
40	JSVM_HandleScope handleScope;
41	OH_JSVM_OpenHandleScope(env, &handleScope);
42
43	// Convert the source code string into a JS string.
44	OH_JSVM_CreateStringUtf8(env, src.c_str(), src.size(), &jsSrc);
45
46	// Compile the JS code.
47	OH_JSVM_CompileScript(env, jsSrc, nullptr, 0, true, nullptr, &script);
48
49	// Run the JS code.
50	JSVM_Value result;
51	OH_JSVM_RunScript(env, script, &result);
52
53	if (dataPtr && lengthPtr && *dataPtr == nullptr) {
54	    // Save the script compiled from the JS source code to the cache to prevent repeated compilation and improve performance.
55	    OH_JSVM_CreateCodeCache(env, script, dataPtr, lengthPtr);
56	}
57
58	OH_JSVM_CloseHandleScope(env, handleScope);
59}
60
61// Use the code cache.
62{
63	JSVM_HandleScope handleScope;
64	OH_JSVM_OpenHandleScope(env, &handleScope);
65
66	// Convert the source code string into a JS string.
67	OH_JSVM_CreateStringUtf8(env, src.c_str(), src.size(), &jsSrc);
68
69	// Use the code cache to compile the JS code.
70	OH_JSVM_CompileScript(env, jsSrc, dataPtr, length, true, &cacheRejected, &script);
71
72	// Run the JS code.
73	JSVM_Value result;
74	OH_JSVM_RunScript(env, script, &result);
75
76	OH_JSVM_CloseHandleScope(env, handleScope);
77}
78```
79
80<!--no_check-->