Skip to content

Commit

Permalink
Optimize: Don't copy Array in Float16Array constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
petamoriken committed Aug 28, 2021
1 parent 2a8d4b0 commit 355f5c4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/Float16Array.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { wrapInArrayIterator } from "./helper/arrayIterator.mjs";
import { isArrayBuffer, isCanonicalIntegerIndexString, isIterable, isObject, isObjectLike, isSharedArrayBuffer, isTypedArray, isUint16Array } from "./helper/is.mjs";
import { isArrayBuffer, isCanonicalIntegerIndexString, isIterable, isObject, isObjectLike, isOrdinaryArray, isSharedArrayBuffer, isTypedArray, isUint16Array } from "./helper/is.mjs";
import { convertToNumber, roundToFloat16Bits } from "./helper/lib.mjs";
import { createPrivateStorage } from "./helper/private.mjs";
import { LengthOfArrayLike, SpeciesConstructor, ToIntegerOrInfinity, defaultCompare } from "./helper/spec.mjs";
Expand Down Expand Up @@ -172,9 +172,17 @@ export class Float16Array extends Uint16Array {

// Iterable (Array)
} else if (isIterable(input)) {
list = [...input];
length = list.length;
super(length);
// for optimization
if (isOrdinaryArray(input)) {
list = input;
length = input.length;
super(length);

} else {
list = [...input];
length = list.length;
super(length);
}

// ArrayLike
} else {
Expand Down
17 changes: 17 additions & 0 deletions src/helper/is.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,23 @@ export function isIterable(value) {
return isObject(value) && typeof value[Symbol.iterator] === "function";
}

/**
* @param {unknown} value
* @returns {value is any[]}
*/
export function isOrdinaryArray(value) {
if (!Array.isArray(value)) {
return false;
}

const iterator = value[Symbol.iterator]();
if (toString.call(iterator) !== "[object Array Iterator]") {
return false;
}

return true;
}

/**
* @param {unknown} value
* @returns {value is string}
Expand Down

0 comments on commit 355f5c4

Please sign in to comment.