Performance gains with null rather than default values?
They say premature optimisation is the root of all evil, but here goes...
We have a high-perfo开发者_如何学JAVArmance application; an in-memory cache backed by Java on the server side and what needs to be a very snappy C# GUI on the client side.
I note that currently the objects we are using in the cache have default values - e.g. initialising Strings by default to "" and Dates to 1/1/1999 rather than leaving them null.
Now I might be being very finicky here, but doesn't this add a tiny bit more space per object (both in the cache and when the object gets serialized) than it would otherwise have if it were null?
Just wondering what sort of improvement (if any) would be gained when our volumes of objects start getting quite high...
Cheers, Dave.
Premature optimization is certainly evil.
But thinking about the performance characteristics of your application and appropriate designs strategies to optimise for performance is perfectly reasonable if performance is a key requirement of the application :-)
A few relevant points:
- There are some (slight) performance benefits from using null rather than a default value. It's easier for the native code to check for a null value than it is to dereference an object reference and examine the value of that object. You probably won't notice this if everything is in L1 cache, but if this causes cache misses in a high-performance application it could become painful.
- There is some extra memory overhead but it probably doesn't matter much - assuming you re-use the same default value objects many times (i.e. many keys point to the same value) then there won't be many extra object instances overall.
- If your default vales are immutable, singleton objects then it helps enormously, for three reasons:
- You only need one copy of the immutable object, rather than different instances of "" (String.intern() helps here!)
- A single object used many times is much more likely to be cached efficiently
- You can use reference equality (value == DEFAULT_SINGLETON) to test for the default value, which avoid the need for a pointer dereference when DEFAULT_SINGLETON is a static final value.
- If you do use immutable singleton default values, be very careful not to get any other instances of the same value mixed in. This can happen e.g. when deserializing objects - you need to use readResolve() etc. to ensure you get the right singleton value in place.
In my opinion, you should probably prefer nulls for default values.
- It's marginally faster and uses less memory
- It is more likely to help you detect a logic error (via a loud NullPointerException rather than causing a difficult-to-track bug with a default value being used in place of a real value)
精彩评论