JavaScript array evolution and performance analysis examples
Before using JavaScript, I was already quite familiar with C, C++, and C#. Like many C/C++ developers, my first impression of JavaScript was not a good one. This article mainly introduces the evolution and performance analysis of JavaScript arrays. This article talks more about memory, optimization, syntax differences, performance, and recent evolution. Friends in need can refer to it, I hope it can help everyone.
Array is one of the main reasons. JavaScript arrays are not contiguous and are implemented like hash-maps or dictionaries. I feel like this is a bit of a B-level language, and the array implementation is simply not appropriate. Since then, JavaScript and my understanding of it have changed, a lot.
Why JavaScript arrays are not real arrays
Before talking about JavaScript, let’s first talk about what Array is.
An array is a contiguous series of memory locations used to hold certain values. It's important to note the emphasis, "continuous" (or contiguous).
The above figure shows how arrays are stored in memory. This array holds 4 elements, each element is 4 bytes. In total, it occupies 16 bytes of memory area.
Suppose we declare tinyInt arr[4];, the address of the allocated memory area starts from 1201. Once you need to read arr[2], you only need to get the address of arr[2] through mathematical calculations. To calculate 1201 + (2 X 4), just start reading directly from 1209.
#Data in JavaScript is a hash map, which can be implemented using different data structures, such as linked lists. So, if you declare an array in JavaScript var arr = new Array(4), the computer will generate a structure similar to the one shown above. If the program needs to read arr[2], it needs to traverse the addressing starting from 1201.
The difference between the above rapid JavaScript arrays and real arrays. Obviously, mathematical calculations are faster than traversing a linked list. This is especially true for long arrays.
The evolution of JavaScript arrays
I wonder if you remember the days when we were so envious of the 256MB computer our friends bought? Today, 8GB of RAM is everywhere.
Similarly, the JavaScript language has also evolved a lot. From V8 and SpiderMonkey to TC39 and the growing number of web users, huge efforts have made JavaScript a world-class necessity. Once you have a huge user base, performance improvement is naturally a hard requirement.
In fact, modern JavaScript engines will allocate contiguous memory for arrays - if the array is homogeneous (all elements are of the same type). A good programmer will always ensure that the array is homogeneous so that the JIT (just-in-time compiler) can read the elements using c compiler-style calculations.
However, once you want to insert an element of another type into a homogeneous array, the JIT will deconstruct the entire array and recreate it in the old way.
So, if your code is not too bad, JavaScript Array objects still remain true arrays behind the scenes, which is extremely important for modern JS developers.
In addition, arrays have evolved more following ES2015/ES6. TC39 decided to introduce typed arrays (Typed Arrays), so we have ArrayBuffer.
ArrayBuffer provides a continuous memory for us to operate at will. However, directly operating memory is still too complex and low-level. So there is a view that handles ArrayBuffer. There are already a few views available, and more will be added in the future.
var buffer = new ArrayBuffer(8); var view = new Int32Array(buffer); view[0] = 100;
High-performance, efficient typed arrays were introduced after WebGL. WebGL workers encounter a huge performance problem, namely how to efficiently handle binary data. Alternatively, you can use SharedArrayBuffer to share data between multiple Web Worker processes to improve performance.
Going from a simple hash map to SharedArrayBuffer, that's pretty cool, right?
Old-style arrays vs typed arrays: Performance
We have discussed the evolution of JavaScript arrays before, now let’s test how much benefits modern arrays can bring us. Here are some micro-test results I ran on a Mac using Node.js 8.4.0.
Old-style array: insert
var LIMIT = 10000000; var arr = new Array(LIMIT); console.time("Array insertion time"); for (var i = 0; i < LIMIT; i++) { arr[i] = i; } console.timeEnd("Array insertion time");
Time taken: 55ms
Typed Array:插入 var LIMIT = 10000000; var buffer = new ArrayBuffer(LIMIT * 4); var arr = new Int32Array(buffer); console.time("ArrayBuffer insertion time"); for (var i = 0; i < LIMIT; i++) { arr[i] = i; } console.timeEnd("ArrayBuffer insertion time");
Time taken: 52ms
Rub, what do I see? Are old-style arrays and ArrayBuffer equally performant? No no no. Remember, as mentioned earlier, modern compilers are smart enough to internally convert traditional arrays of the same element type into memory-contiguous arrays. This is exactly the case with the first example. Despite the use of new Array(LIMIT), the array still exists as a modern array.
Then modify the first example and change the array to a heterogeneous type (the element types are not completely consistent) to see if there is a performance difference.
旧式数组:插入(异构) var LIMIT = 10000000; var arr = new Array(LIMIT); arr.push({a: 22}); console.time("Array insertion time"); for (var i = 0; i < LIMIT; i++) { arr[i] = i; } console.timeEnd("Array insertion time");
Time taken: 1207ms
The change occurs in line 3, adding a statement to change the array into a heterogeneous type. The rest of the code remains unchanged. The performance difference shows up, 22 times slower.
Old-style array: read
var LIMIT = 10000000; var arr = new Array(LIMIT); arr.push({a: 22}); for (var i = 0; i < LIMIT; i++) { arr[i] = i; } var p; console.time("Array read time"); for (var i = 0; i < LIMIT; i++) { //arr[i] = i; p = arr[i]; } console.timeEnd("Array read time");
Time taken: 196ms
Typed Array:读取 var LIMIT = 10000000; var buffer = new ArrayBuffer(LIMIT * 4); var arr = new Int32Array(buffer); console.time("ArrayBuffer insertion time"); for (var i = 0; i < LIMIT; i++) { arr[i] = i; } console.time("ArrayBuffer read time"); for (var i = 0; i < LIMIT; i++) { var p = arr[i]; } console.timeEnd("ArrayBuffer read time");
Time taken: 27ms
Conclusion
The introduction of typed arrays is a big step in the development of JavaScript. Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, these are typed array views, using native endianness (same as native). We can also create custom view windows using DataView. Hopefully there will be more DataView libraries that help us easily manipulate ArrayBuffers in the future.
The evolution of JavaScript arrays is very nice. Now they are fast, efficient, robust, and smart enough in memory allocation.
The above is the detailed content of JavaScript array evolution and performance analysis examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Title: Is Tencent’s main programming language Go: An in-depth analysis. As China’s leading technology company, Tencent has always attracted much attention in its choice of programming languages. In recent years, some people believe that Tencent mainly adopts Go as its main programming language. This article will conduct an in-depth analysis of whether Tencent's main programming language is Go, and give specific code examples to support this view. 1. Application of Go language in Tencent Go is an open source programming language developed by Google. Its efficiency, concurrency and simplicity are loved by many developers.

Analysis of the advantages and limitations of static positioning technology With the development of modern technology, positioning technology has become an indispensable part of our lives. As one of them, static positioning technology has its unique advantages and limitations. This article will conduct an in-depth analysis of static positioning technology to better understand its current application status and future development trends. First, let’s take a look at the advantages of static positioning technology. Static positioning technology achieves the determination of position information by observing, measuring and calculating the object to be positioned. Compared with other positioning technologies,
