apache / apache/rocketmq

[Enhancement] Replace Enum.values() loop with static array lookup in LanguageCode and SerializeType

Open Beginner friendly
#10,511 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
22.6k
Forks
12k
Avg merge
3d 1h
Merged PRs (30d)
27

Description

### Before Creating the Enhancement Request

- [x] I have confirmed that this should be classified as an enhancement rather than a bug/feature.

### Summary

`LanguageCode.valueOf(byte)` and `SerializeType.valueOf(byte)` currently call `values()` in a loop on every invocation. Since JDK requires `Enum.values()` to return a fresh array each time (defensive copy), this allocates a new array per call. Replace with a static `BY_CODE[]` array for O(1) lookup with zero allocation.

### Motivation

JFR `settings=profile` shows these `valueOf(byte)` methods are called on every RPC decode path. `values()` creates a new array on every call — a per-RPC allocation that is completely unnecessary since the enum constants are fixed at class load time.

### Describe the Solution You'd Like

```java
// LanguageCode.java
private static final LanguageCode[] BY_CODE;
static {
LanguageCode[] all = values();
int max = 0;
for (LanguageCode lc : all) {
max = Math.max(max, lc.code & 0xFF);
}
BY_CODE = new LanguageCode[max + 1];
for (LanguageCode lc : all) {
BY_CODE[lc.code & 0xFF] = lc;
}
}

public static LanguageCode valueOf(byte code) {
int idx = code & 0xFF;
return idx < BY_CODE.length ? BY_CODE[idx] : null;
}
```

Same pattern for `SerializeType` (which only has 2 values: JSON=0, ROCKETMQ=1).

### Describe Alternatives You've Considered

- **HashMap**: Adds boxing overhead (`Byte.valueOf`) and more memory than a simple array. Array lookup is simpler and faster.
- **Switch statement**: Not applicable since the lookup key is a `byte` parameter, not a compile-time constant.

### Additional Context

This is the same pattern used in PR #10469 for `MessageVersion.valueOfMagicCode()` (merged).

Contributor guide

Open the contributing guide

Research direction

Start by reading LanguageCode.java and SerializeType.java, focusing on their valueOf(byte) implementations and enum codes. Compare the approach with merged PR #10469 for MessageVersion.valueOfMagicCode(). Done means both methods use static array lookups without per-call values() allocation while preserving the current lookup behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend, performance
Issue type
Feature
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
72/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.