In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "the summary of knowledge points of WebAssembly and its API". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the summary of knowledge points of WebAssembly and API".
What is WebAssembly?
Before we learn about WebAssembly, let's take a look at what Assembly is.
Assembly (Assembly) is a low-level programming language, which is closely related to the machine-level instructions of the architecture. In other words, it only takes one process to convert it into machine-understandable code, that is, machine code. This conversion process is called assembly.
WebAssembly can be referred to as the compilation of Web for short. It is a low-level language similar to assembly language with a compact binary format that allows you to run Web applications at a native-like speed. It also provides compilation goals for languages such as CJE C + + and Rust, enabling client applications to run on Web with near-native performance.
In addition, WebAssembly appears to run with JS, not to replace JS. With WebAssembly JavaScript API, you can run code from either language alternately without any problems going back and forth. This provides us with applications that take advantage of the power and performance of WebAssembly and the versatility and adaptability of JS. This opens up a whole new world for web applications to run code and features that were not originally intended for web.
What's the difference
Lin Clark predicts that the introduction of WebAssembly in 2017 may trigger a new inflection point in the life of web developers. Another early inflection point was when JITs compilation was introduced, which made JS nearly 10 times faster.
If you compare the compilation process of WebAssembly with that of JS, you will notice that several procedures have been stripped and the rest have been trimmed, as shown below:
JIT is a way to make JavaScript run faster, optimizing hot code (code that is executed repeatedly) by monitoring the running status of the code. In this way, the performance of JavaScript applications can be improved many times.
Compare the image above carefully and notice that re-participation in WebAssembly has been completely deprived. This is mainly because the compiler does not need to make any assumptions about the WebAssembly code, because data types such as data types are explicitly mentioned in the code.
But this is not the case with JS, because JIT should make some assumptions to run the code, and if the assumptions fail, it needs to re-optimize its code.
How to get the WebAssembly code
WebAssembly is a great technology. How can we take advantage of the power of WebAssembly?
There are several ways:
It is not recommended to write WebAssembly code from scratch unless you know the basics very well
Compile from C to WebAssembly
Compile from C++ to WebAssembly
Compile from Rust to WebAssembly
Use AssemblyScript to compile Typescript to WebAssembly. For Web developers who are not familiar with C + + or Rust, this is a good choice.
More language options are supported.
In addition, there are tools such as Emscripten and WebAssembly Studio that can help you with the above process.
WebAssembly API of JS
In order to take full advantage of the features of WebAssembly, we must integrate it with JS code, which can be done with the help of JavaScript WebAssembly API.
Module compilation and instantiation
The WebAssembly code resides in the .wasm file. This file should be compiled into machine code specific to the machine on which it is running. We can use the WebAssembly.compile method to compile the WebAssembly module.
The WebAssembly.instantiate method instantiates the compiled module. Alternatively, we can pass the array buffer obtained from the .wasm file to the WebAssembly.instantiate method. This also applies because the instantiation method has two overloads.
Let exports fetch ('sample.wasm') .then (response = > response.arrayBuffer ()) .then (bytes = > WebAssembly.instantiate (bytes)) .then (results = > {exports = results.instance.exports})
One of the disadvantages of the above methods is that they do not have direct access to the bytecode, so additional steps are required to convert the response to ArrayBuffer before compiling / instantiating the wasm module.
Instead, we can use the WebAssembly.compileStreaming / WebAssembly.instantiateStreaming method to achieve the same functionality as above, with the advantage of directly accessing the bytecode without having to convert the response to ArrayBuffer.
Let exports WebAssembly.instantiateStreaming (fetch ('sample.wasm')) .then (obj = > {exports = obj.instance.exports})
Note that WebAssembly.instantiate and WebAssembly.instantiateStreaming return the instance and the compiled module, which can be used to quickly start the instance of the module.
Let exports; let compiledModule; WebAssembly.instantiateStreaming (fetch ('sample.wasm')) .then (obj = > {exports = obj.instance.exports; / / access compiled module compiledModule = obj.module;})
Import object
When you instantiate an WebAssembly module instance, you can choose to pass an import object that will contain values to import into the newly created module instance, which can be of four types:
Global values
Functions
Memory
Tables
You can think of an imported object as a tool provided to a module instance to help it accomplish its task. If no import object is provided, the compiler assigns a default value.
Global
The WebAssembly.Global object represents a global variable instance that can be accessed by JavaScript and importable/exportable, spanning one or more WebAssembly.Module instances. It allows dynamic connections by multiple modules.
You can use the WebAssembly.Global () constructor to create a global instance.
Const global = new WebAssembly.Global ({value: 'i64percent, mutable: true}, 20)
Grammar
Var myGlobal = new WebAssembly.Global (descriptor, value)
The global constructor takes two parameters.
Descriptor
A table with 2 attributes in GlobalDescriptor:
Value: a USVString represents the data type of the global variable. It can be i32, i64, F32, or f64
Mutable: Boolean values determine whether they can be modified. Default is false
Value can be any variable value, and its type needs to match the variable type. If the variable is not defined, use 0 instead
Const global = new WebAssembly.Global ({value: 'i64, mutable: true}, 20); let importObject = {js: {global}}; WebAssembly.instantiateStreaming (fetch (' global.wasm'), importObject)
The global instance should be passed to importObject so that it can be accessed in the WebAssembly module instance.
Memory
When the WebAssembly module is instantiated, it needs a memory object. You can create a new WebAssembly.Memory and pass the object. If no memory object is created, it will be automatically created when the module is instantiated and passed to the instance.
The JS engine creates an ArrayBuffer to do this. ArrayBuffer is a JavaScript object referenced by JS. JS allocates memory for you. You tell it how much memory it needs, and it will create an ArrayBuffer of the corresponding size.
ArrayBuffer does two things, one is to do the memory of WebAssembly, and the other is to do the object of JavaScript.
It makes it easier to pass content between JS and WebAssembly.
Make memory management more secure.
Table
The WebAssembly.Table () constructor creates a Table object based on the given size and element type.
This is a Javascript wrapper object that wraps WebAssemble Table, has a class array structure, and stores multiple function references. Creating Table objects in JS or WebAssemble can be accessed and changed simultaneously by JS or WebAssemble.
The main reason for introducing Table is to improve security. We can manipulate the table using the set (), grow (), and get () methods.
Case study
To demonstrate, I will use the WebAssembly Studio application to compile the C file to .wasm.
I have created a function in the wasm file to calculate the power of a number. I pass the necessary values to the function and then use JavaScript to receive the output.
Again, I did some string manipulation in wasm. Note that wasm does not have a string type. Therefore, it will use the ASCII value. The value returned to JS points to the memory location where the output is stored. Because the memory object is ArrayBuffer, I iterate until I receive all the characters in the string.
JavaScript file
Let exports; let buffer; (async () = > {let response = await fetch ('.. / out/main.wasm'); let results = await WebAssembly.instantiate (await response.arrayBuffer ()); / / or / / let results = await WebAssembly.instantiateStreaming (fetch ('.. / out/main.wasm')); let instance = results.instance; exports = instance.exports; buffer = new Uint8Array (exports.memory.buffer); findPower (5Dome 3); printHelloWorld ();}) () Const findPower = (base = 0, power = 0) = > {console.log (exports.power (base,power));} const printHelloWorld = () = > {let pointer = exports.helloWorld (); let str = ""; for (let I = pointer;buffer [I]; iTunes +) {str + = String.fromCharCode (buffer [I]);} console.log (str);}
C file
# define WASM_EXPORT _ attribute__ ((visibility ("default") # include WASM_EXPORT double power (double number,double power_value) {return pow (number,power_value);} WASM_EXPORT char* helloWorld () {return "hello world";}
Application
WebAssembly is more suitable for writing module, to undertake a variety of complex calculations, such as image processing, 3D operation, speech recognition, video and audio coding and decoding, the main program is still written in javascript.
Thank you for your reading, the above is the "summary of knowledge points of WebAssembly and its API" content, after the study of this article, I believe you have a deeper understanding of the summary of knowledge points of WebAssembly and API, the specific use of the situation also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.