What performance overhead do IoC containers involve?

后端 未结 3 1682
暖寄归人
暖寄归人 2021-02-06 06:25

Loose coupling is wonderful of course, but I have often wondered what overhead wiring up dynamically using an IoC container (for example Castle Windsor) has over a tightly coupl

3条回答
  •  难免孤独
    2021-02-06 06:47

    The best way to understand how complex an IoC container is comes from analyzing it.

    In a particular experience, once I took an entire afternoon debugging some simple 'Hello World' code using plexus, which Maven is based upon (and here is a helpful link to browse its source code). It kinda came up (by looking at defaultPlexusContainer) as:

    • Classpath Configuration (via classworlds)
    • Creation of a Runtime Context Variable (basically a map), in order to store properties and variables
    • Configuration Parsing (discovery of modules metadata on classpath, etc)
    • Initialization:
      • Construction / Instantiation of Services
    • Firing additional ComponentDiscoverers
    • Firing of additional ComponentDiscovererListeners

    This leaves an important aspect, deep into the steps above: Looking up a component. In plexus, the Phase concept wraps the steps for the construction of an Object, and those Phases are usually bound to a Personality concept. However, for the default setting, this is done by executing the following phases:

    • Object Instantiation (i.e., new Object())
    • Log Enabling (i.e., setting a logger for the object)
    • Composition: i.e, dependency lookup and setting
      • The setter strategy is an interesting point, but I will leave the details for now
    • The passing of the Context into the created object
    • The object additional startup procedure

    Most of those steps are optional, and usually involve identifying a given interface and calling it on the target object - this is the default for the plexus personality, note that.

    Also, each object might be bound to a lifecycle manager, which mostly makes the difference between a new object and a singleton.

    In my particular record: The most difficult part is actually parsing the configuration, and booting the container. After that, you're likely to notice no further difference in performance.

提交回复
热议问题