[Enhancement] Set initial capacity for ProxyContext internal HashMap to avoid resize
### Before Creating the Enhancement Request
- [x] I have confirmed that this should be classified as an enhancement rather than a bug/feature.
### Summary
`ProxyContext` (in `org.apache.rocketmq.proxy.common`) uses a `HashMap` with the default initial capacity (16) and default load factor (0.75) to hold context entries. The resize threshold is therefore `12`.
In typical request paths, the context is populated with the 10 standard keys defined in `ContextVariable` (`remote-address`, `local-address`, `client-id`, `channel`, `language`, `client-version`, `remaining-ms`, `action`, `protocol-type`, `namespace`) plus additional entries injected via `withVal(...)` from various processors / interceptors. As soon as the entry count exceeds 12, the underlying `HashMap` triggers a rehash/resize on the hot request path, which is unnecessary overhead given that the upper bound of entries is well-known.
### Motivation
`ProxyContext` is created on every inbound request (gRPC / Remoting), so this resize cost is paid per RPC. Pre-sizing the map eliminates a guaranteed reallocation + rehash on a hot path with effectively zero downside (the extra memory footprint is negligible, ~256 bytes per context).
### Describe the Solution You'd Like
Initialize the internal map with an explicit initial capacity (suggest `64`) so that under the default load factor the threshold (`48`) comfortably exceeds the realistic upper bound of context entries, and no resize will happen on the request path.
```java
// proxy/src/main/java/org/apache/rocketmq/proxy/common/ProxyContext.java
private static final int DEFAULT_INITIAL_CAPACITY = 64;
private final Map<String, Object> value = new HashMap<>(DEFAULT_INITIAL_CAPACITY);
```
### Describe Alternatives You've Considered
- Keep using the default capacity — rejected, incurs a deterministic resize on every request once entries cross 12.
- Use a smaller capacity such as 32 — works for most cases but still risks resize when interceptors/plugins push more values; 64 leaves comfortable headroom while staying small.
- Switch to a different map implementation (e.g. `IdentityHashMap`, array-backed) — out of scope; preserving `HashMap` semantics with a tuned initial capacity is the minimal change.
### Additional Context
File: `proxy/src/main/java/org/apache/rocketmq/proxy/common/ProxyContext.java`
Related code:
- `ProxyContext#value` field — the map being resized.
- `ContextVariable` — defines 10 well-known keys, all of which are usually set during a single request lifecycle.
Happy to send a PR.
关闭于 2026-06-11 4 条评论