# Socket#recv into a buffer

**URL:** <https://www.ruby-forum.com/t/socket-recv-into-a-buffer/137863>\
**Category:** Ruby\
**Created:** [May 17, 2008, 12:51am UTC](https://www.ruby-forum.com/t/socket-recv-into-a-buffer/137863 "2008-05-17T00:51:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Joel\_VanderWerf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e19b73/32.png) [@Joel\_VanderWerf](https://www.ruby-forum.com/u/Joel_VanderWerf)\
**Post date:** [May 17, 2008, 12:51am UTC](https://www.ruby-forum.com/t/socket-recv-into-a-buffer/137863/1 "2008-05-17T00:51:00Z")

</div>

Is there any reason why Socket#recv can’t take an optional buffer  
argument the way IO#read does?

Otherwise, Socket#recv is always allocating strings, hence burdening GC.

I saw about a 20% improvement by using #read instead of #recv in some  
socket code, but of course the unbuffered vs. buffered difference comes  
into play there too.

---

<div class="post-metadata">

**Author:** ![Joel\_VanderWerf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e19b73/32.png) [@Joel\_VanderWerf](https://www.ruby-forum.com/u/Joel_VanderWerf)\
**Post date:** [May 18, 2008, 6:19am UTC](https://www.ruby-forum.com/t/socket-recv-into-a-buffer/137863/2 "2008-05-18T06:19:07Z")

</div>

Joel VanderWerf wrote:

> Is there any reason why Socket#recv can’t take an optional buffer  
> argument the way IO#read does?
> 
> Otherwise, Socket#recv is always allocating strings, hence burdening GC.
> 
> I saw about a 20% improvement by using #read instead of #recv in some  
> socket code, but of course the unbuffered vs. buffered difference comes  
> into play there too.

Sounds like it would make a good patch. I think the reason it’s not is  
that [afaik] ruby typically doesn’t have default lengths for  
strings…i.e. if recv returns less than the desired number of bytes,  
ruby ‘tends’ to return a string of exactly that length [and that much  
memory allocated] so…in our hypothetical example above, it  
should…leave it still large? [i.e. it would require string itself to change].  
That being said, you CAN have a string with extra nulls in it  
“abc\0def” and that’s a valid string, so maybe recv\_into\_string could  
just write out something like that…  
thoughts?  
-R
