Summary of Differences between php Array and Linked List
- 2021-12-21 04:31:35
Difference between Array and Linked List in PHP
From the perspective of logical structure
1. The array must be defined in advance with a fixed length (the number of elements), which cannot adapt to the dynamic increase or decrease of data. When the data increases, it may exceed the number of elements originally defined; When the data is reduced, the memory is wasted; Arrays can be accessed directly according to subscripts.
2. The linked list is dynamically allocated, which can adapt to the dynamic increase and decrease of data, and can conveniently insert and delete data items. (When inserting or deleting data items in the array, other data items need to be moved, which is very cumbersome.) The linked list must find the next 1 element according to next pointer.
From the point of view of memory storage
1. (Static) Array allocates space from the stack, which is convenient and fast for programmers, but has little freedom.
2. The linked list allocates space from the heap, which has great freedom, but it is troublesome to apply for management.
As you can see from the above comparison, if you need to access data quickly, with little or no insertion and deletion of elements, you should use arrays; On the contrary, if you need to insert and delete elements frequently, you need to use linked list data structures.
Array is to store elements continuously in memory. Because each element occupies the same memory, any element in the array can be quickly accessed through subscripts. But if you want to add one element to the array, you need to move a large number of elements, make space for one element in memory, and then put the elements to be added in it.
By the same token, if you want to delete an element, you also need to move a large number of elements to fill out the moved element. If your application needs fast access to data with little or no insertion and deletion of elements, you should use arrays.
In a linked list, on the contrary, elements in a linked list are not stored sequentially in memory, but are linked to 1 by pointers existing in the elements. For example, the first element has a pointer to the next element, and so on, until the last element.
If you want to access an element in a linked list, you need to start with the first element, and 1 will find the required element position. But adding and deleting an element is very simple for the linked list data structure, as long as you modify the pointer in the element. If the application needs to insert and delete elements frequently, you need to use linked list data structure.
The above is all the knowledge points introduced this time. Thank you for reading and supporting this site.