注意:这不是 Minecraft Fabric 特有的。我只是刚接触严格的运行前优化。
我正在为 Minecraft 模组编写一个 API 挂钩,它允许将各种任务映射到村民的“职业”属性,允许其他模组为自定义职业添加自定义任务。我已经完成了所有后端代码,所以现在我担心优化。
我有一个ImmutableMap.Builder<VillagerProfession, VillagerTask>
用来存储其他模组添加的任务的。问题是,虽然我知道永远不会在运行时调用“put”方法,但我不知道编译器是否这样做。显然,由于这是一款游戏,并且模组包中的启动时间已经很长,我想尽可能地优化它,因为每个希望添加新村民任务的模组都会使用它。
这是我当前的“任务注册表”源代码:
private static final ImmutableMap.Builder<VillagerProfession, ImmutableList<Pair<Task<? super VillagerEntity>, Integer>>> professionToVillagerTaskBuilder = ImmutableMap.builder();
private static final ImmutableMap<VillagerProfession, ImmutableList<Pair<Task<? super VillagerEntity>, Integer>>> professionToVillagerTaskMap;
// The hook that any mods will use in their source code
public static void addVillagerTasks(VillagerProfession executingProfession, ImmutableList<Pair<Task<? super VillagerEntity>, Integer>> task)
{
professionToVillagerTaskBuilder.put(executingProfession, task);
}
//The tasklist retrieval method used at runtime
static ImmutableList<Pair<Task<? super VillagerEntity>, Integer>> getVillagerRandomTasks(VillagerProfession profession)
{
return professionToVillagerTaskMap.get(profession);
}
static { // probably not the correct way to do this, but it lets me mark the map as final
professionToVillagerTaskMap = professionToVillagerTaskBuilder.build();
}
谢谢!