Prefer using Array.Length as upper for loop limit#2513
Conversation
|
Thanks! |
|
Just for a take-away, I have two questions (apologies if it is an improper place to ask): Length caching before for loop is a noticeable practice (perhaps for micro-optimization of IL or some devs have this habit as some sort of good practice). Does that mean from JIT's perspective, not doing such optimization in user code is more profitable because it hinders JITs ability to perform range check elimination optimization? Is it not feasible for JIT to detect the collection length, perhaps only to the extent when it is defined/cached explicitly in the local scope of method? For instance, recently this PR has brought similar caching of length for performance optimization: dotnet/corefxlab#1113. |
Correct - for loops over arrays. Caching length may help slightly for loops over collections, but it is not 100% rule. You need to measure the concrete piece code to get the ultimate answer.
It is possible, but the current .NET JITs do not have this optimization. In general, explicit caching is typically not worth it for state that is known to be immutable to the JIT. It is typically worth it for potentially mutable state, e.g.: vs. |
FWIW, the corefxlab change adds hoisting for iteration over |
|
RyuJIT has several deficiencies wrt. Span codegen right now. The missing range check optimization is one of them. They will get fixed before |
Port of dotnet/coreclr#8923