Skip to content

Commit 8cd00ba

Browse files
committed
use native fn when possible
1 parent d78efb9 commit 8cd00ba

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

packages/browser-utils/src/getNativeImplementation.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ interface CacheableImplementations {
1515

1616
const cachedImplementations: Partial<CacheableImplementations> = {};
1717

18+
/**
19+
* isNative checks if the given function is a native implementation
20+
*/
21+
// eslint-disable-next-line @typescript-eslint/ban-types
22+
function isNative(func: Function): boolean {
23+
return func && /^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString());
24+
}
25+
1826
/**
1927
* Get the native implementation of a browser function.
2028
*
@@ -32,8 +40,14 @@ export function getNativeImplementation<T extends keyof CacheableImplementations
3240
return cached;
3341
}
3442

35-
const document = WINDOW.document;
3643
let impl = WINDOW[name] as CacheableImplementations[T];
44+
45+
// Fast path to avoid DOM I/O
46+
if (isNative(impl)) {
47+
return (cachedImplementations[name] = impl.bind(WINDOW) as CacheableImplementations[T]);
48+
}
49+
50+
const document = WINDOW.document;
3751
// eslint-disable-next-line deprecation/deprecation
3852
if (document && typeof document.createElement === 'function') {
3953
try {
@@ -62,8 +76,7 @@ export function getNativeImplementation<T extends keyof CacheableImplementations
6276

6377
/** Clear a cached implementation. */
6478
export function clearCachedImplementation(name: keyof CacheableImplementations): void {
65-
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
66-
delete cachedImplementations[name];
79+
cachedImplementations[name] = undefined;
6780
}
6881

6982
/**

0 commit comments

Comments
 (0)