经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
前端 Array.sort() 源码学习
来源:cnblogs  作者:二价亚铁  时间:2024/6/28 9:32:54  对本文有异议

源码地址

V8源码Array
710行开始为sort()相关

Array.sort()方法是那种排序呢?

去看源码主要是源于这个问题

  1. // In-place QuickSort algorithm.
  2. // For short (length <= 22) arrays, insertion sort is used for efficiency.

源码中的第一句话就回答了我的问题

  1. // 通常使用快速排序算法
  2. // 如果数组长度小于23,则插入排序效率更好

既然都打开了,索性就看看源码叭,看看sort到底做了些啥
我把一整坨源码码分成一块一块来看,让自己比较清晰的知道sort到底干了些啥,下面是阅读代码时,自己的思路梳理

第一块代码

  1. if (!IS_CALLABLE(comparefn)) {
  2. comparefn = function (x, y) {
  3. if (x === y) return 0;
  4. if (%_IsSmi(x) && %_IsSmi(y)) {
  5. return %SmiLexicographicCompare(x, y);
  6. }
  7. x = TO_STRING(x);
  8. y = TO_STRING(y);
  9. if (x == y) return 0;
  10. else return x < y ? -1 : 1;
  11. };
  12. }

第一块内容判断,如果传进来的参数不可回调,则给一个默认的回调函数
这个回调函数,判断俩值是不是Smi

  1. // Smi:小整数(Small integers)V8引擎中的元素类型之一
  2. `https://medium.com/@justjavac/v8-internals-how-small-is-a-small-integer-ba5e17a3ae5f`
  3. // PS: markdown语法有问题,这里直接贴出 url

如果是则进行小整数字典序比较
什么是字典序

否则将两个值转换成字符串进行字符串比较大小
字符串如何比较大小

第二块代码

  1. var InsertionSort = function InsertionSort(a, from, to) {
  2. ...
  3. };
  4. var QuickSort = function QuickSort(a, from, to) {
  5. if (to - from <= 10) {
  6. InsertionSort(a, from, to);
  7. return;
  8. }
  9. ...
  10. };

第二块就是正常的快速排序和插入排序
这里采取的是数量小于10的数组使用 InsertionSort(插入),比10大的数组则使用 QuickSort(快速)。

第三块代码

  1. if (!is_array) {
  2. // For compatibility with JSC, we also sort elements inherited from
  3. // the prototype chain on non-Array objects.
  4. // We do this by copying them to this object and sorting only
  5. // own elements. This is not very efficient, but sorting with
  6. // inherited elements happens very, very rarely, if at all.
  7. // The specification allows "implementation dependent" behavior
  8. // if an element on the prototype chain has an element that
  9. // might interact with sorting.
  10. max_prototype_element = CopyFromPrototype(array, length);
  11. }

这块代码里面的注释,讲的还是比较详细的,百度翻译也非常nice

  1. // 为了与JSC兼容,我们还在非数组对象上对从原型链继承的元素进行排序。
  2. // 我们通过将它们复制到这个对象并只对自己的元素排序来实现这一点。
  3. // 这不是很有效,但是使用继承的元素进行排序的情况很少发生,如果有的话。
  4. // 如果原型链上的元素具有可能与排序交互的元素,则规范允许“依赖于实现”的行为。

第四块代码

  1. // Copy elements in the range 0..length from obj's prototype chain
  2. // to obj itself, if obj has holes. Return one more than the maximal index
  3. // of a prototype property.
  4. var CopyFromPrototype = function CopyFromPrototype(obj, length) {
  5. var max = 0;
  6. for (var proto = %object_get_prototype_of(obj);
  7. proto;
  8. proto = %object_get_prototype_of(proto)) {
  9. var indices = IS_PROXY(proto) ? length : %GetArrayKeys(proto, length);
  10. if (IS_NUMBER(indices)) {
  11. // It's an interval.
  12. var proto_length = indices;
  13. for (var i = 0; i < proto_length; i++) {
  14. if (!HAS_OWN_PROPERTY(obj, i) && HAS_OWN_PROPERTY(proto, i)) {
  15. obj[i] = proto[i];
  16. if (i >= max) { max = i + 1; }
  17. }
  18. }
  19. }
  20. else {
  21. for (var i = 0; i < indices.length; i++) {
  22. var index = indices[i];
  23. if (!HAS_OWN_PROPERTY(obj, index) && HAS_OWN_PROPERTY(proto, index)) {
  24. obj[index] = proto[index];
  25. if (index >= max) { max = index + 1; }
  26. }
  27. }
  28. }
  29. }
  30. return max;
  31. };

这块代码是对于非数组的一个处理
注释里面说到

  1. // 如果obj有holes(能猜出大概意思,不咋好翻译这个hole)
  2. // 就把obj原型链上0-length所有元素赋值给obj本身
  3. // 返回一个max,max是比原型属性索引最大值+1

返回的max会在下面用到

第五块代码

  1. if (!is_array && (num_non_undefined + 1 < max_prototype_element)) {
  2. // For compatibility with JSC, we shadow any elements in the prototype
  3. // chain that has become exposed by sort moving a hole to its position.
  4. ShadowPrototypeElements(array, num_non_undefined, max_prototype_element);
  5. }

注释翻译:

  1. // 为了与JSC兼容
  2. // 我们对原型链中通过sort将一个hole移动到其位置而暴露的所有元素
  3. // 进行shadow处理。

可能因为英语语法水平不够,单看注释还有点不明白
大致意思是,把“掀开的东西,再盖上”
直接看下面一块代码,看看这个shadow操作到底干了啥叭

第六块代码

  1. // Set a value of "undefined" on all indices in the range from..to
  2. // where a prototype of obj has an element. I.e., shadow all prototype
  3. // elements in that range.
  4. var ShadowPrototypeElements = function(obj, from, to) {
  5. for (var proto = %object_get_prototype_of(obj); proto;
  6. proto = %object_get_prototype_of(proto)) {
  7. var indices = IS_PROXY(proto) ? to : %GetArrayKeys(proto, to);
  8. if (IS_NUMBER(indices)) {
  9. // It's an interval.
  10. var proto_length = indices;
  11. for (var i = from; i < proto_length; i++) {
  12. if (HAS_OWN_PROPERTY(proto, i)) {
  13. obj[i] = UNDEFINED;
  14. }
  15. }
  16. }
  17. else {
  18. for (var i = 0; i < indices.length; i++) {
  19. var index = indices[i];
  20. if (from <= index && HAS_OWN_PROPERTY(proto, index)) {
  21. obj[index] = UNDEFINED;
  22. }
  23. }
  24. }
  25. }
  26. };

这块代码就是shadow操作,注释翻译如下:

  1. // 在范围从..到obj原型包含元素的所有索引上设置一个“undefined”值。
  2. // 换句话说
  3. // 在该范围内对所有原型元素进行shadow处理。

其中:
I.e.是拉丁文id est 的缩写,它的意思就是“那就是说,换句话说”
英文不够你用了是不你还要写拉丁文?!

果然大致的意思猜的没错
在刚刚把对象的原型属性的复制,现在要设置undefined来shadow他了

第七块代码

  1. if (num_non_undefined == -1) {
  2. // There were indexed accessors in the array.
  3. // Move array holes and undefineds to the end using a Javascript function
  4. // that is safe in the presence of accessors.
  5. num_non_undefined = SafeRemoveArrayHoles(array);
  6. }

意思是 数组中有索引访问器。使用JS函数将数组hole和未定义项移到末尾,该函数在访问器存在时是安全的。
下面是安全移出数组hole方法

  1. var SafeRemoveArrayHoles = function SafeRemoveArrayHoles(obj) {
  2. // Copy defined elements from the end to fill in all holes and undefineds
  3. // in the beginning of the array. Write undefineds and holes at the end
  4. // after loop is finished.
  5. var first_undefined = 0;
  6. var last_defined = length - 1;
  7. var num_holes = 0;
  8. while (first_undefined < last_defined) {
  9. // Find first undefined element.
  10. while (first_undefined < last_defined &&
  11. !IS_UNDEFINED(obj[first_undefined])) {
  12. first_undefined++;
  13. }
  14. // Maintain the invariant num_holes = the number of holes in the original
  15. // array with indices <= first_undefined or > last_defined.
  16. if (!HAS_OWN_PROPERTY(obj, first_undefined)) {
  17. num_holes++;
  18. }
  19. // Find last defined element.
  20. while (first_undefined < last_defined &&
  21. IS_UNDEFINED(obj[last_defined])) {
  22. if (!HAS_OWN_PROPERTY(obj, last_defined)) {
  23. num_holes++;
  24. }
  25. last_defined--;
  26. }
  27. if (first_undefined < last_defined) {
  28. // Fill in hole or undefined.
  29. obj[first_undefined] = obj[last_defined];
  30. obj[last_defined] = UNDEFINED;
  31. }
  32. }
  33. // If there were any undefineds in the entire array, first_undefined
  34. // points to one past the last defined element. Make this true if
  35. // there were no undefineds, as well, so that first_undefined == number
  36. // of defined elements.
  37. if (!IS_UNDEFINED(obj[first_undefined])) first_undefined++;
  38. // Fill in the undefineds and the holes. There may be a hole where
  39. // an undefined should be and vice versa.
  40. var i;
  41. for (i = first_undefined; i < length - num_holes; i++) {
  42. obj[i] = UNDEFINED;
  43. }
  44. for (i = length - num_holes; i < length; i++) {
  45. // For compatability with Webkit, do not expose elements in the prototype.
  46. if (i in %object_get_prototype_of(obj)) {
  47. obj[i] = UNDEFINED;
  48. } else {
  49. delete obj[i];
  50. }
  51. }
  52. // Return the number of defined elements.
  53. return first_undefined;
  54. };

还会判断数组长度

  1. if (length < 2) return array;

原文链接:https://www.cnblogs.com/xw-01/p/18266079

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号