MethodImplOptions.AggressiveInlining at last with .Net Framework 4.5

So, in this kinda blog page, I’ll be also trying to comment on language & framework other than talking about my stuff. With the latest huge array technique with flatten array support, I do now use block pointer functions and here’s one;

        /// <summary>
        /// Returns block index by relative position of block in chunk.
        /// </summary>
        /// <param name="chunk">The chunk block belongs to.</param>
        /// <param name="x">Blocks relative x position in chunk.</param>
        /// <param name="y">Blocks y position in chunk.</param>
        /// <param name="z">Blocks relative x position in chunk.</param>
        /// <returns></returns>
        public static int BlockIndexByRelativePosition(Chunk chunk, byte x, byte y, byte z)
            var xIndex = chunk.WorldPosition.X + x;
            var zIndex = chunk.WorldPosition.Z + z;

            var wrapX = xIndex % CacheWidthInBlocks;
            var wrapZ = zIndex % CacheLenghtInBlocks;

            var flattenIndex = wrapX * FlattenOffset + wrapZ * Chunk.HeightInBlocks + y;
            return flattenIndex;

All code in the engine that access block data has to use one of these functions and it’s really not a good idea to repeat the code all over the source (given that a possible future update on functions will require lots of time and will make it harder to maintain and hunt for bugs). Although today’s modern compilers are quite intelligent, still I was eager for some forced inlining functionality given that those functions get calls millions of times. Statement lambdas are a possibility but they’re technically not what I’m looking for;

Conventional way:
L_0000: nop 
L_0001: ldarg.0 
L_0002: ldarg.1 
L_0003: ldarg.2 
L_0004: ldarg.3 
L_0005: call int32 VolumetricStudios.VoxeliqGame.Chunks.BlockCache::BlockIndexByRelativePosition(class VolumetricStudios.VoxeliqGame.Chunks.Chunk,
 uint8, uint8, uint8)

Statement Lambdas:
L_0000: nop 
L_0001: ldsfld class [mscorlib]System.Func5<class VolumetricStudios.VoxeliqGame.Chunks.Chunk, uint8, uint8, uint8,
 int32> VolumetricStudios.VoxeliqGame.Chunks.BlockCache::BlockIndexByRelativePosition3
L_0006: ldarg.0 
L_0007: ldarg.1 
L_0008: ldarg.2 
L_0009: ldarg.3 
L_000a: callvirt instance !4 [mscorlib]System.Func`5<class VolumetricStudios.VoxeliqGame.Chunks.Chunk, uint8, uint8, uint8, int32>::Invoke(!0, !1, !2, !3)

So at last .Net 4.5 will be coming with a new Method Implementation Option called AggressiveInlining. MSDN has the following explanation;

  • AggressiveInlining: The method should be inlined if possible. It’ll be nice to force regular functions to get inlined with 4.5.

Update: You can find a nice reading on it over here.

Leave a Reply

Your email address will not be published. Required fields are marked *