Home >Web Front-end >Front-end Q&A >Where does javascript array subscript start?
Javascript array subscripts start from 0, reasons: 1. Starting from 0 can reduce one subtraction operation, reduce CPU instruction operations, and improve CPU efficiency; 2. The address of physical memory starts from 0 .
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript array subscripts start from 0.
So why does JavaScript array subscript start from 0 instead of 1?
Reason 1: Historical reasons
The order of language appearance is from early to late C, Java, and JavaScript.
C language array subscripts start from 0 ->Java also ->JavaScript also.
Reduce additional learning and understanding costs.
Reason 2: Reduce CPU instruction operations
(1) The subscript starts from 0:
Array addressing - arr[i] = base_address i * type_size (1)
where base_address is the first address of array arr, arr0 is the array with offset 0, that is, the first address of array arr; i is the offset, type_size is the number of bytes of the array type , for example, int is 32 bits, which is 4 bytes.
(2) The subscript starts from 1:
Array addressing - arr[i] = base_address (i -1) * type_size (2)
Compare the two From the calculation formula, we can find that formula (2) requires one more i-1 operation for each CPU addressing, that is, one more subtraction instruction operation.
For basic data structures such as arrays, no matter which high-level programming language, they are frequently used indirectly (as the basic data structure of the container, such as Java's ArrayList) or directly, so it should be minimized. It consumes CPU resources. Starting from 0, one subtraction operation can be reduced, which improves the efficiency of the CPU.
Reason 3: The address of physical memory starts from 0
Computer main memory is an array composed of multiple consecutive byte-sized units, each byte They all correspond to unique physical addresses, and the address of the first byte is 0.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of Where does javascript array subscript start?. For more information, please follow other related articles on the PHP Chinese website!