Extra stack generated by ClassCastException for target type check
Hi, Thanks for the great library.
Our flame graph shows there are extra stacks from creating ClassCastException
.
By looking code, there are many of try-catch of ClassCastException
to check whether the instance is a target type or not.
Since creation of ClassCastException
creates extra stacks, it is better to check by !=null
&& instanceof
.
For example, in SimpleJwkFilter
:
String getCrv(JsonWebKey jwk)
{
try
{
return ((EllipticCurveJsonWebKey) jwk).getCurveName();
}
catch (ClassCastException e)
{
return null;
}
}
This can be written:
String getCrv(JsonWebKey jwk)
{
// in this case, jwk is guaranteed to be not null, skipping null check
if(!(jwk instanceof EllipticCurveJsonWebKey)) {
return null;
}
return ((EllipticCurveJsonWebKey) jwk).getCurveName();
}
It is a tiny portion compare to entire application stack, but it is appreciated if you could remove try-catch, so that extra stack generation can be avoided.
Comments (4)
-
repo owner -
reporter Hi Brian,
I personally prefer instanceof for readability, but I'm not an expert which is faster or better in the matter of try-catch vs instanceof. So, I don't mind how it is to follow the style in this library.
Just I found this flame graph while I was looking at for my app. It is just a tiny stack compare to the entire application stack.
If you need to do performance tuning, this may be one of the area to consider since this extra stack would consume tiny bit of extra memory/cpu.
For now, I think it is nice to know information and I don't have strong needs to update it.
-
repo owner - changed status to resolved
-
repo owner - changed status to closed
released in jose4j-0.7.0 https://bitbucket.org/b_c/jose4j/wiki/Release%20Notes#!jose4j-070-january-17-2019
- Log in to comment
A long time ago I read something that said casting in a try/catch with ClassCastException was better performant than using
instanceof
and I guess that got me in the habit of doing it that way. I don't know if it's actually any better or worse. And I suspect it doesn't really make a difference one way or the other. But I'd consider a pull request, if this is something that's important to you.