I saw an example of a Valhalla value class that represents a ticker using a single int field. How would that work, and is it worth trying in real code while Valhalla is still in preview?
Can a ticker symbol really fit in one int?
Answers
It can work if you define a restricted alphabet and maximum length. For example, five bits per character can encode up to 32 possible values, so six characters fit in 30 bits. You also need a way to distinguish shorter symbols, such as reserving one value as a terminator.
That is a compact representation, not a universal ticker format. Decide which characters and lengths you need, reject anything outside that set, and make sure encoding and decoding round-trip correctly.
Reply to this answer
For a production migration, I would experiment in a branch first rather than build a big dependency on preview behavior. Value classes are interesting, but preview features can change before they become permanent.
Keep the encoding behind a small API and measure the actual memory and throughput effects for your workload. A single int field is compact, but that alone doesn't tell you how every instance or collection will be laid out.
v.672!marlixo:
Keeping the encoding separate from the preview class sounds useful. That would let the experiment change without changing the symbol rules.
Reply to this answer
The one-int example also brings up a separate question about flattening larger value classes. Atomic reads and writes are part of that discussion, but a single int example doesn't establish what the JVM will do with a larger value.
Past behavior for long values on 32-bit JVMs is an interesting comparison, though it doesn't by itself settle the design tradeoffs for value classes.
Reply to this answer
Add your answer
Answers are reviewed before publication.
c.497~drivnaro:
Also decide how to handle lowercase input. Normalizing it and rejecting it are both possible, but they give callers different expectations.