Skip to content

Commit a89e932

Browse files
fkgozalifacebook-github-bot
authored andcommitted
Cache Platform constants in JS
Summary: For better perf with TurboModule, cache the return value of NativePlatformConstants*.getConstants() in JS so that we avoid going back into native (from JS) for each call. This specific method is called very frequently throughout RN codebase. Reviewed By: mdvacca Differential Revision: D15893289 fbshipit-source-id: ce8016ed7d3efb420df93e27dbfa77d7d4f06cf8
1 parent 99ece27 commit a89e932

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

Libraries/Utilities/Platform.android.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,21 +18,25 @@ export type PlatformSelectSpec<A, D> = {
1818
};
1919

2020
const Platform = {
21+
__constants: null,
2122
OS: 'android',
2223
get Version() {
23-
return NativePlatformConstantsAndroid.getConstants().Version;
24+
return this.constants.Version;
2425
},
2526
get constants() {
26-
return NativePlatformConstantsAndroid.getConstants();
27+
if (this.__constants == null) {
28+
this.__constants = NativePlatformConstantsAndroid.getConstants();
29+
}
30+
return this.__constants;
2731
},
2832
get isTesting(): boolean {
2933
if (__DEV__) {
30-
return NativePlatformConstantsAndroid.getConstants().isTesting;
34+
return this.constants.isTesting;
3135
}
3236
return false;
3337
},
3438
get isTV(): boolean {
35-
return NativePlatformConstantsAndroid.getConstants().uiMode === 'tv';
39+
return this.constants.uiMode === 'tv';
3640
},
3741
select: <A, D>(spec: PlatformSelectSpec<A, D>): A | D =>
3842
'android' in spec ? spec.android : spec.default,

Libraries/Utilities/Platform.ios.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,19 @@ export type PlatformSelectSpec<D, I> = {
1818
};
1919

2020
const Platform = {
21+
__constants: null,
2122
OS: 'ios',
2223
get Version() {
23-
return NativePlatformConstantsIOS.getConstants().osVersion;
24+
return this.constants.osVersion;
2425
},
2526
get constants() {
26-
return NativePlatformConstantsIOS.getConstants();
27+
if (this.__constants == null) {
28+
this.__constants = NativePlatformConstantsIOS.getConstants();
29+
}
30+
return this.__constants;
2731
},
2832
get isPad() {
29-
return NativePlatformConstantsIOS.getConstants().interfaceIdiom === 'pad';
33+
return this.constants.interfaceIdiom === 'pad';
3034
},
3135
/**
3236
* Deprecated, use `isTV` instead.
@@ -35,11 +39,11 @@ const Platform = {
3539
return Platform.isTV;
3640
},
3741
get isTV() {
38-
return NativePlatformConstantsIOS.getConstants().interfaceIdiom === 'tv';
42+
return this.constants.interfaceIdiom === 'tv';
3943
},
4044
get isTesting(): boolean {
4145
if (__DEV__) {
42-
return NativePlatformConstantsIOS.getConstants().isTesting;
46+
return this.constants.isTesting;
4347
}
4448
return false;
4549
},

0 commit comments

Comments
 (0)