A function I want to Spring-inject takes varargs. Should I provide an overload that takes a list instead?

不羁的心 提交于 2020-01-05 04:55:18

问题


I have a factory method to box up some order-dependent Things:

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

public class ThingBoxProcessor {
    public static ThingBox forInputThings(Thing... thingsToProcess) {
       ThingBox thingBox = new ThingBox();
       for (Thing thing : Lists.reverse(ImmutableList.copyOf(thingsToProcess))) {
          thingBox.store(thing);
       }
       return thingBox;
    }
}

And I inject it like so:

<bean name="Things" class="ThingBoxProcessor" factory-method="forInputThings">
   <constructor-arg>
      <list>
         <ref bean="ThingTwo" />
         <ref bean="ThingOne" />
         <!-- imagine a couple dozen other things that do different order-sensitive things -->
      </list>
   </constructor-arg>
</bean>

Is Spring creating an ArrayList, then converting it to an array? Is there any significant performance advantage to offering an overload such as:

    public static ThingBox forInputThings(Thing... thingsToProcess) {
       return forInputThings(ImmutableList.copyOf(thingsToProcess));
    }

    public static ThingBox forInputThings(List<Thing> thingsToProcess) {
       ThingBox thingBox = new ThingBox();
       for (Thing thing : Lists.reverse(thingsToProcess)) {
          thingBox.store(thing);
       }
       return thingBox;
    }

(This question isn't what I'm interested in. I know I can inject a spring xml list into a varargs param; I just want to know if there are performance reasons to do otherwise.)


回答1:


I would not dedicate any time to this problem because:

Assuming that you are dealing with singleton scoped Spring beans, this operation is going to happen once.

Plus: starting up a Spring context will take at least a few seconds since it needs to read config files, load classes, etc. Compared to this the penalty for converting back and forth between arrays and lists of any reasonable size (reasonable in a sense that you would probably not put more than 50? of your parameters into Spring), will likely add around 0,000001% to your boot-speed.

So from reliability, maintainability or some similar point of view it makes sense to think about which option you should choose, but performance-wise it is really as irrelevant as it gets.



来源:https://stackoverflow.com/questions/39542043/a-function-i-want-to-spring-inject-takes-varargs-should-i-provide-an-overload-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!