What will be the best way to optimize below code?
protected void saveUserRoles(Set<String> userRoles) {
if (userRoles != null && (userRoles.contains(StaticValues.LUMEN_SELECT_USER_ROLE)
|| userRoles.contains(StaticValues.EASY_SENSE_USER_ROLE)
|| userRoles.contains(StaticValues.TLED_USER_ROLE)||userRoles.contains(StaticValues.IR_APP_USER_ROLE))) {
preferences.setUserRoles(userRoles);
}
}
I suggest you just keep a list or array of the values to test against:
private static final List USER_ROLES_TO_SAVE = Arrays.asList(
StaticValues.LUMEN_SELECT_USER_ROLE,
StaticValues.EASY_SENSE_USER_ROLE,
StaticValues.TLED_USER_ROLE,
StaticValues.IR_APP_USER_ROLE);
protected void saveUserRoles(Set<String> userRoles) {
if (userRoles == null) {
return;
}
for (String candidate : USER_ROLES_TO_SAVE) {
if (userRoles.contains(candidate)) {
preferences.setUserRoles(userRoles);
return;
}
}
}
That's now very easy to maintain and read - and as for performance, if you're only looking at expanding the list to about 8 entries, there's no point in trying to get fancy - I would be absolutely astonished if this became the bottleneck, and finding anything faster in terms of complexity than O(N) is unlikely to be useful given how small N is in this case.
See more on this question at Stackoverflow