Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performant way to detect immutables?

I have a utility that is designed to pass objects around our system. Because it is a multithreaded environment, the utility makes a deep copy of each object it passes to prevent any thread safety issues. I'm working on transitioning our system to use immutable objects to eliminate the need for this copy. I'm wonder what is the best (fastest) way to detect that the object is immutable?

My first thought was to just to pick up on the attribute that we put on all our immutable objects (MessageAttribute). As you can see from the performance profile below, it takes quite a hit (roughly 10x the time to execute as all my other checks).

enter image description here

How else can I detect my immutables passing through? I can just do a typeof() comparison, which appears way more performant, but this seems pretty unwieldy, and it will be hell to maintain as we add more immutables all the time.

EDIT: I forgot to mention that the boolean values are refactored out into variables for the purpose of profiling, in reality, the expressions who's result is stored in isDefined is actually in the else if statement, so would be hit about 10x less that shown in this profile (I'm more concerned with the average execution time than the absolute execution time though).

like image 947
GBleaney Avatar asked Dec 25 '22 17:12

GBleaney


2 Answers

Make an interface (eg. IImmutable) and use it on all your immutable classes.

You only have to check for this interface with typeof() to detect an immutable.

typeof() is a compile time check, so you have no performance hit.

like image 116
thumbmunkeys Avatar answered Dec 28 '22 05:12

thumbmunkeys


You are using isDefined only in the else branch which is hit 10x less then the then branch. Only compute the value when needed. That should cut its cost by 10x.

Apart from that you could introduce a cache for the computation. There are probably very few types that you ever inspect, so the cache would be small.

like image 21
usr Avatar answered Dec 28 '22 05:12

usr