Scrafty Gaming Scrafty Gaming - 4 months ago 13
Java Question

Any other way to optimize this?

So my code is:

public void checkArmor() {
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
for (Player p : Bukkit.getOnlinePlayers()) {
if (p.getInventory().getBoots().getType() == Material.CHAINMAIL_BOOTS
&& p.getInventory().getLeggings().getType() == Material.CHAINMAIL_LEGGINGS
&& p.getInventory().getChestplate().getType() == Material.CHAINMAIL_CHESTPLATE
&& p.getInventory().getHelmet().getType() == Material.CHAINMAIL_HELMET) {
p.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 20, 0));
p.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 20, 1));
p.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 20, 0));
}
if (p.getInventory().getBoots().getType() == Material.LEATHER_BOOTS
&& p.getInventory().getLeggings().getType() == Material.LEATHER_LEGGINGS
&& p.getInventory().getChestplate().getType() == Material.LEATHER_CHESTPLATE
&& p.getInventory().getHelmet().getType() == Material.LEATHER_HELMET) {
p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 20, 1));
p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 20, 1));
p.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 20, 1));
}
if (p.getInventory().getBoots().getType() == Material.IRON_BOOTS
&& p.getInventory().getLeggings().getType() == Material.IRON_LEGGINGS
&& p.getInventory().getChestplate().getType() == Material.IRON_CHESTPLATE
&& p.getInventory().getHelmet().getType() == Material.IRON_HELMET) {
p.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 20, 0));
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20, 1));
p.addPotionEffect(new PotionEffect(PotionEffectType.HEALTH_BOOST, 20, 1));
}
if (p.getInventory().getBoots().getType() == Material.GOLD_BOOTS
&& p.getInventory().getLeggings().getType() == Material.GOLD_LEGGINGS
&& p.getInventory().getChestplate().getType() == Material.GOLD_CHESTPLATE
&& p.getInventory().getHelmet().getType() == Material.GOLD_HELMET) {
p.addPotionEffect(new PotionEffect(PotionEffectType.SATURATION, 20, 2));
p.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, 140, 0));
p.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 20, 1));
p.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 20, 1));
}
}
}
}, 0, 10);
}


I'd like to know if there's any more way to optimize this? I've asked around in bukkit and spigot, but no one really gave me any tips, so I've come here.
Also, before it reapplies the effect it lets the potion effect run out first, instead of reapplying it every half second.

Answer

You are calling the same methods over and over again. Why not call them only once and assign the results to some variable, like

leggingsType = p.getInventory().getLeggings().getType();

I don't really think that this makes a huge performance difference but it will make the code more readable.