Discussions about Java versus C performance usually revolve around benchmarks from the internet and end with a conclusion everyone knew before the conversation started. We landed a project where we had to settle it on our own data, because the system’s architecture depended on the answer. We wrote the same decoder four times, twice in Java and twice in C, and measured everything on identical files. The results were more interesting than we expected.
The problem: files that can’t wait
Binary billing records flow in from the core of a telecom network at regular intervals. The format is the industry standard: ASN.1 encoded with BER rules, plus optional zlib compression. Each file holds a hundred-odd thousand records and weighs tens of megabytes, and from every record we have to extract 21 fields out of more than fifty available and write them in columnar form for the data warehouse.
Today’s scale: about 10 million records per day. The scale from the growth projections the system has to be sized for: over 200 million per day within a few years. On top of that, a hard time window, because each batch of files must be processed before the next one arrives, i.e. within a dozen or so minutes. And one more requirement that is easy to forget at the design stage: the ability to reprocess history from scratch when the set of fields changes or we find a bug in the mapping. Then we are not decoding one batch, but months of data.
The decoder is the heart of this pipeline. Everything else, file transport, validation, loading into the warehouse, is ordinary plumbing. So before choosing a technology, we decided to actually test a few variants instead of going on gut feeling.
Four decoders instead of one
BER is a TLV format: tag, length, value, recursively all the way down. There are two ways to approach such a format. Either you take an ASN.1 library that generates or builds full data structures from the specification, or you write your own parser that knows only the tags you care about and skips the rest. Crossing these two approaches with two languages gave us four implementations:
- Java with an ASN.1 library, which decodes records into generated classes, and we just copy the fields over.
- Java with a hand-written BER parser, a manual loop over tags, about 2,000 lines including tests.
- C with code generated by an ASN.1 compiler (asn1c), over 200 generated source files plus a thin mapping layer.
- C with a hand-written BER parser, written from scratch for this one record type, just under 800 lines.
Sounds like overkill, but it was not expensive. TLV formats are quick to parse, and three of the four variants were built in a single working day each. We treated it as an investment in a decision we would then have to maintain for years.
What it looks like in code
The core of every parser is the same: a loop reading consecutive TLVs and a dispatch on the tag. In Java it looks like this:
BerReader reader = new BerReader(content);
UsageRecordBuilder b = new UsageRecordBuilder();
while (reader.hasMore()) {
BerTag tag = reader.readTag();
int length = reader.readLength();
byte[] value = reader.readValue(length);
switch (tag.toHexString()) {
case "83" -> b.subscriberId = FieldDecoders.decodeTbcd(value);
case "87" -> b.accessPoint = FieldDecoders.decodeIA5String(value);
case "8D" -> b.openingTime = FieldDecoders.decodeTimestamp(value);
case "8E" -> b.duration = (int) FieldDecoders.decodeInteger(value);
case "BF22" -> parseServiceDataList(value, b);
default -> { } // tags we don't need
}
}
return b.build();Readable, testable, pleasant to maintain. But let’s look at what happens
inside readValue():
public byte[] readValue(int length) {
byte[] value = new byte[length]; // allocation for every field
buf.get(value); // copy bytes out of the buffer
return value;
}Every field of every record is a fresh byte array on the heap plus a copy of the data. Add an object per tag, a String per decoded value, a builder object per record. Decoding a million records with twenty-odd fields each produces tens of millions of short-lived objects that the GC has to clean up after us.
The C version does exactly the same thing logically, but copies not a single byte:
int ber_read_tlv(const uint8_t *p, int avail, BerTlv *tlv)
{
/* ...parse tag and length... */
if (off + tlv->length > avail) return -1;
tlv->value = p + off; /* pointer into the input buffer, zero copies */
tlv->total_bytes = off + tlv->length;
return tlv->total_bytes;
}A TLV value is a pointer into the memory-mapped file buffer. The record
structure lives on the stack and is overwritten in place for every subsequent
record. There is not a single malloc during the whole file decode. Field
decoders write straight into the output buffers:
char *decode_tbcd(const uint8_t *data, int len, char *buf)
{
char *p = buf;
for (int i = 0; i < len; i++) {
int lo = data[i] & 0x0F;
int hi = (data[i] >> 4) & 0x0F;
if (lo < 10) *p++ = '0' + lo; else if (lo == 0xF) break;
if (hi < 10) *p++ = '0' + hi; else if (hi == 0xF) break;
}
*p = '\0';
return buf;
}The same decoder in Java means a StringBuilder and a String on output.
Individually that is nothing; multiplied by hundreds of millions of calls, it
makes a difference you will see in the table in a moment.
Results
Benchmark: 250 thousand records in files totalling 48 MB, uncompressed, single thread. The environment was deliberately modest, an ordinary VM from our internal test infrastructure: 4 vCPUs on shared cores, 8 GB RAM, Ubuntu, ext4. No exotic hardware, and that is important context for the numbers below, because any production machine with dedicated cores can only improve on what you see in the table. Every decoder got identical data, and we averaged the result over many runs, after warming up the JVM where applicable.
| Decoder | Time | Records/s | vs. fastest |
|---|---|---|---|
| C, hand-written BER parser | 0.23 s | ~1,090,000 | 1.0× |
| Java, ASN.1 library | 1.45 s | ~172,000 | 6.3× slower |
| C, code generated from ASN.1 | 5.6 s | ~45,000 | 24× slower |
| Java, hand-written BER parser | 10.9 s | ~23,000 | 47× slower |
Two things in this table matter more than the ranking itself.
First, the spread within one language was larger than between languages. The two C programs are 24× apart. The two Javas are 7× apart. If someone compared only the second and third variants, they would conclude that Java is several times faster than C, and within that comparison they would be right.
Second, the best Java beat C with a generated library by a factor of four. The
code generated by asn1c is correct and complete, but it pays for generality:
it allocates and frees a full tree of structures for every record, including
fields nobody reads. The JVM’s JIT with a good streaming library had an easier
job here than malloc and free called millions of times.
The hand-written Java parser came last, and that was no surprise, because we
deliberately wrote it readability-first: immutable objects, buffer copies, a
builder per record. Exactly what good application code in Java looks like. So
this result does not say someone wrote it badly. It says how much, in this
particular task, it costs to use the style we rightly choose day to day for
maintainability. This variant could be sped up considerably by switching to
copy-free ByteBuffer views and reusable objects, but then we would be writing
C in Java syntax and losing the readability that, as it turned out, kept this
code around for the long haul. More on that in a moment.
Observation. Performance was decided not by the language, but by the memory model. The winning variant won not because it was in C, but because it allocated nothing. The language was the tool that allowed this without fighting its own idioms.
What went to production
The hand-written C parser went to production, wrapped in a simple CLI: files in, columnar text out, invoked by the pipeline as a separate process. After expanding from the trimmed field set to the full format, throughput dropped to about 420 thousand records per second per thread, still on the same 4-vCPU VM, which at our volumes means:
- the current batch of files: a fraction of a second, against a window measured in minutes,
- a full day of data: under half a minute on a single thread,
- reprocessing a month of history after a schema change: a dozen or so minutes instead of an overnight maintenance window.
In practice, decoding stopped existing as a line item in the system’s time budget. The headroom over the growth projections is large enough that scaling comes down to turning up the number of parallel processes, should it ever be needed.
Couldn’t Java have handled it? Today, it could. The fastest Java variant would process the current day’s data in a few minutes and fit in the window. The decision was settled by the projections, the full format and the history reprocessing scenario, under which the headroom shrank from years to hours. We preferred to settle it once, at a stage where the change cost one Makefile, not a migration of a running system.
Maintenance, the other side of the coin
C in production sounds like a recipe for trouble, and we took that risk seriously, because a pointer bug in an input-data parser is a textbook vulnerability. A few things mean that after a year in operation we still sleep well.
Small, boring code. The whole parser is just under 800 lines of C with not a single allocation and one dependency, the system zlib. You can read it end to end in one afternoon, which makes it genuinely auditable. The debug build compiles with AddressSanitizer and UBSan, and the tests also feed it corrupted data and data truncated at random points.
Java didn’t leave the project. It stayed where it is at its best. Our Java module generates synthetic test files in a format binary-compatible with production, has over a hundred tests with full encode/decode round-trips, and serves as the reference implementation. A comparison test decodes the same files with Java and with C, then compares the results field by field. Every change to the C parser has to pass through this gate. That took the biggest maintenance burden off C: we don’t have to trust that it is correct, because we check it automatically on every change.
The boundary of responsibility is narrow. C does one thing: it reads bytes and writes text. All the business logic, orchestration and pipeline error handling live outside it, in technologies where changes are cheap. If the source format changed often, the maths would look different, because adding a field to a hand-written parser means manual work on the tag dispatch, whereas an ASN.1 library would get it from regenerating the schema. Our format changes rarely, and that settled it.
Conclusions
There is no single answer to the question of whether Java is slower than C. The fastest Java in this comparison was four times faster than the slower C. There is, however, an answer to the question of what to do when performance really matters: measure on your own data, across several variants, before the architecture sets the choice in concrete. And if the result pushes you towards C, narrow its responsibility to the minimum and keep a comfortable reference implementation in a language where tests are pleasant to write. For us, this split, C decodes and Java guards correctness, has proven more durable than any single benchmark.