@
wheeler 赞同
实际上,calloc 的实现在多数操作系统的实现和 malloc 几乎一样快,比如 Linux/FreeBSD 内核可能会直接返回 pre zero-mapped pages。
> You're likely to still see a performance improvement without overcommit. The OS will try to zero free pages in the background, so there's a good chance that it'll have pre-zeroed pages to hand you when you ask for them, rather than making you wait for them to be zeroed on demand.
Of course, there are plenty of systems where this doesn't happen, or there are no pages in the first place, or there's no kernel zeroing stuff for you.
回到问题本身,我觉得这个可能是历史原因,早期 calloc 作为一个库函数用于消除平台之间内存分配的差异,当初实现初始化零也是直接按字节填零操作的,可能是出于防御性编程的考虑(当时可能还没有这种概念),方便 debug。可能和 @
wheeler 所说的类似,零内存使用场景并不大,而且清零还费时(当时机器性能可不如现在这么强大),malloc 孕育而生。大部分情况下申请内存之后我们都会填入一些数据,这样来看,使用 malloc 可以获得 performance agin。
> So the (slightly modified) question still stands: Why do calloc and malloc exist? Indeed it looks like calloc was originally intended as a portable way to allocate memory. It used the function alloc which apparently was not meant to be used directly; most iolib functions have a 'c' tacked on. So when iolib was reworked into the stdlib why was calloc kept? saretired suspects backward compatibility but I don't believe this, because no other c-prefixed iolib function was kept and i couldn't find any code that actually used calloc in the v6 distribution either. So maybe whoever is responsible for malloc/calloc in v7 (I think it was ken, not dmr) thought malloc should be a public function but saw a use for calloc and changed the semantics to be a bit more predictable.
see:
https://news.ycombinator.com/item?id=13108434如果什么地方说的不对,麻烦指正。:-P