How are arrays implemented in Perl?

霸气de小男生 提交于 2020-01-13 07:46:31

问题


The Perl array is an abstract data type. What's the internal mechanism for the Perl array? Is it implemented with dynamic array or linked list? Since the array elements have random access, I would assume a dynamic array of pointers, or references to scalars make sense. However, with shift and unshift operation at the head of array, would the array have to move all its elements with these operations? sound inefficient to me. Any thought?


回答1:


Have a look at this: http://www.perlmonks.org/?node_id=17890

(taken from there:)

Perl implements lists with an array and first/last element offsets. The array is allocated larger than needed with the offsets originally pointing in the middle of the array so there is room to grow in both directions (unshifts and pushes/inserts) before a re-allocation of the underlying array is necessary. The consequence of this implementation is that all of perl's primitive list operators (insertion, fetching, determining array size, push, pop, shift, unshift, etc.) perform in O(1) time.




回答2:


The types are documented in the perlguts (see Perl Internals for related documentation) - and are AV for arrays and HV for hashes.



来源:https://stackoverflow.com/questions/3130336/how-are-arrays-implemented-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!