C is Brittle D is Plastic
Walter Bright
newshound2 at digitalmars.com
Sun Mar 22 04:47:41 UTC 2026
It's true that writing code in C doesn't automatically make it faster.
For example, string manipulation. 0-terminated strings (the default in C) are,
frankly, an abomination. String processing code is a tangle of strlen, strcpy,
strncpy, strcat, all of which require repeated passes over the string looking
for the 0. (Even worse, reloading the string into the cache just to find its
length makes things even slower.)
Worse is the problem that, in order to slice a string, a malloc is needed to
copy the slice to. And then carefully manage the lifetime of that slice.
The fix is simple - use length-delimited strings. D relies on them to great
effect. This can be done in C, but there is no succor from the language, and
such a package is not standardized. I've proposed a simple enhancement for C to
make them work https://www.digitalmars.com/articles/C-biggest-mistake.html but
nobody in the C world has any interest in it (which is baffling, as it is so
simple!).
Another source of slowdown in C that became apparent over the years is C is a
brittle language, rather than a plastic one. The first algorithm selected for a
C project gets so welded into it that it cannot be changed without great
difficulty. (And we all know that algorithms are the key to speed, not coding
details.) Why does this happen with C?
It's because one cannot switch back and forth between a reference type and a
value type without extensively rewriting every use of it. For example:
```C
struct S { int a; }
int foo(struct S s) { return s.a; }
int bar(struct S *s) { return s->a; }
```
To switch between reference and value, it's necessary to go through all the code
swapping . and ->. It's just too tedious and never happens. In D:
```D
struct S { int a; }
int foo(S s) { return s.a; }
int bar(S *s) { return s.a; }
```
Working on D shows that there is no reason for the C and C++ -> operator to even
exist, the . operator covers both bases!
More information about the Digitalmars-d
mailing list