Object.isArray()很慢,有没有快速的方法呢? [英] Object.isArray() is slow, is there a fast way to do that?
问题描述
在我的应用程序中 obj.getClass()。isArray()
被频繁调用并成为应用程序的瓶颈。
我想要如果对象是数组,则在运行时有效地检查。
原始数组和对象数组应返回true。
我可以想象的方式是 instanceof
所有原始数组,但不能处理像INT [] []。该应用程序用作lib,所以我不能列出所有类型。
是否有任何线索?
我刚刚完成的基准测试给出了以下结果:
{s instanceof Object []}花费44ms
{s.getClass()。getName()。charAt(0)=='['}花费58ms
{s.getClass()。isArray()}花费303ms
已使用 Benchmark.java ,使用 Main.java 进行调用。
在上述基准测试中讨论了 final
变量的使用后,请参阅新的结果使用本地结果:
{s instanceof Object []}花费83ms
{s.getClass()。getName()。charAt(0)=='['}花费93ms
{s.getClass()。isArray()}花费354ms
即使持续时间有点长(有趣的顺便说一句),他们的订单也已保留。
然后使用这个新的 Main.java 调用Benchmark.java。 / p>
并使用另一个调用的原始数组 Main.java :
{a instanceof int []花费71ms
{a.getClass()。getName()。charAt(0)=='['}花费82ms
{a.getClass()。isArray()}花费340ms
结果订单仍然相同。
In my application obj.getClass().isArray()
is called very frequently and become the bottleneck of the app.
I want to check efficiently at run-time if an object is an array.
Primitive array and object array should return true.
The way I can imagine is to instanceof
all primtive arrays, but cannot handle types like int[][]. And the app is used as lib, so I cannot list all types.
Is there any clue for that?
A benchmark I've just done gave the following results:
{s instanceof Object[]} spends 44ms
{s.getClass().getName().charAt(0) == '['} spends 58ms
{s.getClass().isArray()} spends 303ms
Benchmark has been done using Benchmark.java, called with Main.java.
After having discussed the use of a final
variable in the above benchmark, see the new results using a local one:
{s instanceof Object[]} spends 83ms
{s.getClass().getName().charAt(0) == '['} spends 93ms
{s.getClass().isArray()} spends 354ms
Even if the durations are all a bit longer (interesting btw), their order has been preserved.
Benchmark.java has been then called with this new Main.java.
And using a primitive array called with this other Main.java:
{a instanceof int[]} spends 71ms
{a.getClass().getName().charAt(0) == '['} spends 82ms
{a.getClass().isArray()} spends 340ms
Still the same results order.
这篇关于Object.isArray()很慢,有没有快速的方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!