简体   繁体   中英

.NET JIT difference while using Factory Pattern and If-else or switch

I was just wandering, if I was to have a one method that handles 100 different cases based upon an enum let's say (assuming each case has on average 5 lines of code), would that actually impact performance ? How about instead of having all the code in one method, the Factory or Strategy pattern would to be used ?

The JIT only compiles the code which is actually needed at that point. So I guess it will compile the hole method of 100 cases right? It wouldn't actually know what part of that method is needed correct ? but if I was to split that method it will actually compile what it is needed right?. For example having an actions drop-down (list of 100 Car Brands)

How would that compare to each other in terms of performance?

Thanks.

I am afraid you are missing the essential thing that Jit does. It compiles cil which is CPU and platform independent into machine and platform specific machine code.

The JIT only compiles the code which is actually needed at that point.

Yes, the very first time your method is called then the Jit compiles it, hence the name Just-In-Time compiler .

So I guess it will compile the hole method of 100 cases right?

Yes.

It wouldn't actually know what part of that method is needed correct ? but if I was to split that method it will actually compile what it is needed right?

Now here the confusion comes, yes it will compile the whole method, but notice this will be only once per application startup. Since, Jit compiles at runtime we can say that there will be some negligible performance impact first time method was called, one can argue that splitting this method into multiple methods will require multiple Jit compilations.

With that being said, if you are working on some very high demand for performance application and you are worrying about Jit being drawback you can always use ngen and compile native images before application start and then CLR can use those images to spin up the process for you and this will remove Jit compilation as it was basically done before application was started. I can see how this might be useful for applications caring about cold startups such as applications hosted on function as a service platforms but thats as far as I can go with the real world examples.

And in the end,

How would that compare to each other in terms of performance?

to be honest I wouldn't be worried ever about Jit compilation impact, I'd rather focus on the data structures I am using or the domain specific logic I have in order to improve my performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM