Skip to content

Instantly share code, notes, and snippets.

@TerribleDev
Last active August 29, 2015 14:27
Show Gist options
  • Save TerribleDev/1cdc415bff3d21f7a484 to your computer and use it in GitHub Desktop.
Save TerribleDev/1cdc415bff3d21f7a484 to your computer and use it in GitHub Desktop.
Jit your application (run at startup)
using System;
using System.Reflection;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
namespace MyApp.AppStart
{
public static class Primer
{
public static void ForEach<T>(
this IEnumerable<T> source,
Action<T> action)
{
foreach (T element in source)
action.Invoke(element);
}
/// <summary>
/// Prime assemblies to be used quickly
/// </summary>
public static void Prime()
{
AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.FullName.Contains("My Assembly") || a.FullName.Contains("MyOtherAssembly"))
.AsParallel()
.ForAll(asm => asm.
GetTypes()
.Where(a => !a.IsAbstract && !a.IsInterface && a.IsClass)
.Select(a => a.GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.Static))
.ForEach(a =>
a.ForEach(b =>
{
try
{
RuntimeHelpers.PrepareMethod(b.MethodHandle);
}
//if we can't jit a few methods its probably fine
#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
#pragma warning disable CC0004 // Catch block cannot be empty
catch { }
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
#pragma warning restore CC0004 // Catch block cannot be empty
})));
//TODO: Think about other files or hash tables that could benefit from being loaded into memory
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment