简体   繁体   中英

Avoid instantiating new objects inside loops in java

I would like to avoid crating the new instance of SelectItem in side the loop. Could you please help me how can i avoid it.

public List<SelectItem> createLocales() {
    final List<SelectItem> enabledLocales = new ArrayList<SelectItem>();
    final List<String> langCodes = labeldbservice.getEnabledLocales();
    LOGGER.debug("getEnabledLocales: size={0}", langCodes);
    for (final String langCode : langCodes) {
        enabledLocales.add(new SelectItem(langCode, LocaleUtils.toLocale(langCode).getDisplayName()));
    }
    return enabledLocales;
}
public List<SelectItem> createLocales() {
    final List<SelectItem> enabledLocales = new ArrayList<SelectItem>();
    final List<String> langCodes = labeldbservice.getEnabledLocales();
    final SelectItem sItem = new SelectItem();

    LOGGER.debug("getEnabledLocales: size={0}", langCodes);
    for (final String langCode : langCodes) {
        sItem.setValue(langCode);
        sItem.setLabel(LocaleUtils.toLocale(langCode).getDisplayName());
        enabledLocales.add(sItem);
    }
    return enabledLocales;
}

I solved this PMD Issue by creating a method which will return a new object. I will call this method in loop to get new object.
For your code it would be something like this.

public List<SelectItem> createLocales() {
    final List<SelectItem> enabledLocales = new ArrayList<SelectItem>();
    final List<String> langCodes = labeldbservice.getEnabledLocales();
    LOGGER.debug("getEnabledLocales: size={0}", langCodes);
    for (final String langCode : langCodes) {
        enabledLocales.add(getNewSelectItem(langCode, LocaleUtils.toLocale(langCode).getDisplayName()));
    }
    return enabledLocales;
}

public SelectItem getNewSelectItem(String langCode, String displayName) {
    return new SelectItem(langCode, displayName);
}

我不明白你为什么要改变这段代码,但假设你已经把它测量为性能瓶颈,要么缓存createLocales的结果(全局或每个Thread使用一个懒惰地构建它的ThreadLocal)或者可能不是返回一个list,将langCode中的映射返回到懒惰实例化的值并缓存所需的SelectItem实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM