Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.isArray() is slow, is there a fast way to do that?

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?

like image 847
Nickolas Avatar asked Apr 23 '13 13:04

Nickolas


People also ask

How do you know if data is object or array?

isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false .

Is array vs Instanceof?

isArray() method is universal, it can function any where whereas instanceof operator is not universal, it can't work in new environment..

Is array instance of object?

We create an array of a specified length and access the elements with the index operator, [] . Unlike other languages, however, arrays in Java are true, first-class objects. An array is an instance of a special Java array class and has a corresponding type in the type system.

Is array in Nodejs?

In order to check if something is an array, you can use Node. js util native module and its isArray() function. FWIW, util. isArray() currently proxies to Array.


1 Answers

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.

like image 117
sp00m Avatar answered Sep 30 '22 19:09

sp00m