Skip to content

ResourceBundleMessageSource performance optimization for getStringOrNull [SPR-13295] #17885

@spring-projects-issues

Description

@spring-projects-issues

Maxim Kirilov opened SPR-13295 and commented

Exception creation is very expensive due to fillStackTrace method (Throwable class). See here stackoverflow post.

The current method implementation replaces the thrown exception with null value.

private String getStringOrNull(ResourceBundle bundle, String key) {
     try {
          return bundle.getString(key);
     }
     catch (MissingResourceException ex) {
          // Assume key not found
          // -> do NOT throw the exception to allow for checking parent message source.
          return null;
     }
}

I suggest to refactor the code to:

private String getStringOrNull(ResourceBundle bundle, String key) {
     try {
          /**
           * ResourceBundle is checked for actually having the key before
           * calling getString. This is because getString will throw an
           * exception if the key is not found. We would like to avoid
           * creating an exception because of fillStackTrace method which is
           * very expensive.
           */
          if (bundle != null && bundle.containsKey(key)) {
               return bundle.getString(key);
          } else {
               return null;
          }
     }
     catch (MissingResourceException ex) {
          // Assume key not found
          // -> do NOT throw the exception to allow for checking parent message source.
          return null;
     }
}

This will eliminate unnessary exception object creation.


Attachments:

Issue Links:

Referenced from: commits 2c2bed2

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions