按类型划分的弹簧布线比按名称布线要慢 [英] Spring wiring by type is slower by magnitude than wiring by name

查看:151
本文介绍了按类型划分的弹簧布线比按名称布线要慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我正在尝试迁移所有用法

In my project, I am trying to migrate all usages of

Foo foo = (Foo) beanFactory.getBean("name");

进入

Foo foo = beanFactory.getBean(Foo.class);

好处是显而易见的:类型安全,代码复杂程度低,无用常量等等。通常这样的行位于静态遗留环境中,这种布线是唯一的选择。

The benefits are obvious: type safety, less convoluted code, less useless constants, etc. Typically such lines are located in static legacy contexts where such a wiring is the only option.

直到有一天用户开始抱怨来自春天的内部。所以我启动了一个分析器来查找热点

This was all fine until one day users started to complain about the slowness which turned out to come from Spring internals. So I fired up a profiler to find a hotspot in

org.springframework.beans.factory.support.AbstractBeanFactory :: doGetBean(String,Class< ; T>,Object [],boolean)

这是一个昂贵的电话

Class.isAssignableFrom(anotherClass)

我已经快速创建了一个小的性能测试来找出字符串名称和类型查找之间的速度差异是 350 次(我正在使用 StaticApplicationContext 进行此测试FAIW)!

I have quickly created a small performance test to find out the speed difference between string name and type lookups is a whooping 350 times (I'm using StaticApplicationContext for this test FAIW)!

在调查此问题时,我发现 SPR-6870 的数量很多投票但由于某种原因未得到解决。这导致我试图解决这个问题,它确实显着改善了这种情况,但仍然比String查找慢了 ~25 倍!事实证明,这种尝试只解决了一半的问题:它缓存了bean的名称以保存在O(n)迭代上,但仍然必须调用 isAssignableFrom 来验证类型。

While investigating this, I found SPR-6870 which has high number of votes but for some reason isn't addressed. This led me to an attempt to solve this problem which does significantly improve the situation but is still slower ~25 times than lookup by String! It turns out this attempt only solves half of the problem: it caches the name of the bean to save on O(n) iteration but still has to do call isAssignableFrom to validate the type.

描述的问题不仅与我的场景有关,而且也适用于使用 @Autowired 的bean在循环中创建bean的情况下会感觉很难。

Described problem is not only related to my scenario but is also for beans which use @Autowired and can be felt hard in cases where beans are created inside a loop.

其中一个解决方案是覆盖其中一个bean工厂方法并缓存is-this-bean-相同类型的检查结果,但显然这应该在Spring中完成,而不是在我自己的代码中。

One of solutions would be to override one of the bean factory methods and cache the is-this-bean-of-the-same-type check results but clearly this should be done in Spring and not in my own code.

是否有其他人患有类似的问题并且发现了它的解决方案是什么?

Is anyone else suffering from a similar problem and found a solution to it?

推荐答案

这个问题现在在Spring中解决,分辨率为 SPR-6870 。有关详细信息,请参阅其中的分辨率该修复程序从版本3.2.0.RELEASE和3.1.2开始提供。

This problem is now solved in Spring with the resolution of SPR-6870. See the resolution comments there for details. The fix is available as of versions 3.2.0.RELEASE and 3.1.2.

这篇关于按类型划分的弹簧布线比按名称布线要慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆