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?
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 .
isArray() method is universal, it can function any where whereas instanceof operator is not universal, it can't work in new environment..
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With