Skip to content

Commit

Permalink
Cache Platform constants in JS
Browse files Browse the repository at this point in the history
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
  • Loading branch information
fkgozali authored and facebook-github-bot committed Jun 19, 2019
1 parent 99ece27 commit a89e932
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
12 changes: 8 additions & 4 deletions Libraries/Utilities/Platform.android.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,25 @@ export type PlatformSelectSpec<A, D> = {
};

const Platform = {
__constants: null,
OS: 'android',
get Version() {
return NativePlatformConstantsAndroid.getConstants().Version;
return this.constants.Version;
},
get constants() {
return NativePlatformConstantsAndroid.getConstants();
if (this.__constants == null) {
this.__constants = NativePlatformConstantsAndroid.getConstants();
}
return this.__constants;
},
get isTesting(): boolean {
if (__DEV__) {
return NativePlatformConstantsAndroid.getConstants().isTesting;
return this.constants.isTesting;
}
return false;
},
get isTV(): boolean {
return NativePlatformConstantsAndroid.getConstants().uiMode === 'tv';
return this.constants.uiMode === 'tv';
},
select: <A, D>(spec: PlatformSelectSpec<A, D>): A | D =>
'android' in spec ? spec.android : spec.default,
Expand Down
14 changes: 9 additions & 5 deletions Libraries/Utilities/Platform.ios.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,19 @@ export type PlatformSelectSpec<D, I> = {
};

const Platform = {
__constants: null,
OS: 'ios',
get Version() {
return NativePlatformConstantsIOS.getConstants().osVersion;
return this.constants.osVersion;
},
get constants() {
return NativePlatformConstantsIOS.getConstants();
if (this.__constants == null) {
this.__constants = NativePlatformConstantsIOS.getConstants();
}
return this.__constants;
},
get isPad() {
return NativePlatformConstantsIOS.getConstants().interfaceIdiom === 'pad';
return this.constants.interfaceIdiom === 'pad';
},
/**
* Deprecated, use `isTV` instead.
Expand All @@ -35,11 +39,11 @@ const Platform = {
return Platform.isTV;
},
get isTV() {
return NativePlatformConstantsIOS.getConstants().interfaceIdiom === 'tv';
return this.constants.interfaceIdiom === 'tv';
},
get isTesting(): boolean {
if (__DEV__) {
return NativePlatformConstantsIOS.getConstants().isTesting;
return this.constants.isTesting;
}
return false;
},
Expand Down

0 comments on commit a89e932

Please sign in to comment.