[SPIGOT-7146] ItemMeta implementations switch over Material, unnecessarily inflating jar size Created: 28/Aug/22  Updated: 25/Dec/24  Resolved: 11/Sep/22

Status: Resolved
Project: Spigot
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Yz Ren Assignee: Parker Hawke
Resolution: Fixed Votes: 0
Labels: None

Attachments: PNG File issue-20220828-0.png    
Version: 1.18.2, or basically all versions
Guidelines Read: Yes

 Description   

Java compiler expands 'switch of a enum type' expression to a synthetic method with name starting with '$SWITCH_TABLE$' which generates an int array to match with the ordinal of enum entries in 'case' expression. Even if you only use one 'case' expression, the compiler will generate method that maps ALL entries in that enum. The int array and method are generated for ALL the classes who 'switched' that enum. When the enum has hundreds of entries, the byte size of that method expand rapidly, and the large method kills decompiler and IDE, increase jar file size, and it's product int array waste runtime memory.

For example, in 1.18.2-R0.1 spigot jar with craftbukkit, CraftMetaBook class, which 'switches' Material enum class with 2 'cases', takes 115,045 bytes, while another class CraftMetaCompass which have no 'switch' to Material enum, takes only 14,541 bytes. The decompilation of CraftMetaBook class takes more than 15s on my computer using FernFlower. Intellij IDEA also lags for that long of time when opening this class.

Be honest, this isn't a big issue when writing code, and it doesn't hit performance a lot. But I think abuse 'switch' expression on large enum class such as Material should not be encouraged and it's considered a bad coding behavior. To reduce such behaviors, we can create some new classes that similar to Items or EntityTypes class in NMS to encourage developers to use 'if' expression. 

At least, I think craftbukkit internal should eliminate these 'switch' expressions as much as possible (as they always give me a suprise when I'm checking implementations)



 Comments   
Comment by Parker Hawke [ 29/Aug/22 ]

Removing use of switch statements in ItemMeta implementations alone shaved of 2MB from the final .jar. I've created a pull request to remove them. Though I've kept two Material switch statements in CraftItemStack and CraftItemFactory because there isn't a great alternative to these switches yet. These are the only two remaining Material switches in CraftBukkit. I'm hoping that this will be improved upon the merge of craftbukkit#931

Generated at Sun Mar 30 17:57:28 UTC 2025 using Jira 10.3.3#10030003-sha1:d220e3fefc8dfc6d47f522d3b9a20c1455e12b7b.