Hacker Monthly #21 by Netizens Media

Hacker Monthly #21 by Netizens Media

Author:Netizens Media [Media, Netizens]
Language: eng
Format: epub, mobi, pdf
Published: 2012-02-02T16:04:10+00:00


You can see that the RString structure contains two values: ptr and len, but not the actual string data itself. Ruby actually saves the string character values themselves in some memory allocated from the heap, and then sets ptr to the location of that heap memory and len to the length of the string.

Here’s a simplified version of the C RString structure:

struct RString {

long len;

char *ptr;

};

I’ve simplified this a lot; there are actually a number of other values saved in this C struct. I’ll discuss some of them next and others I’ll skip over for today. If you’re not familiar with C, you can think of struct (short for “structure”) as an object that contains a set of instance variables, except in C there’s no object at all – struct is just a chunk of memory containing a few values.

I refer to this type of Ruby string as “Heap String” since the actual string data is saved in the heap.

Shared Strings

Another type of string value that the Ruby interpreter uses is called a “Shared String” in the Ruby C source code. You create a Shared String every time you write a line of Ruby code that copies one string to another, similar to this:

str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"

str2 = str

Here the Ruby interpreter has realized that you are assigning the same string value to two variables: str and str2. So in fact there’s no need to create two copies of the string data itself. Instead, Ruby creates two RString values that share the single copy of the string data. The way this works is that both RString structs contain the same ptr value to the shared data… meaning both strings contain the same value. There’s also a shared value saved in the second RString struct that points to the first RString struct. There are some other details, which I’m not showing here, such as some bit mask flags that Ruby uses to keep track of which RStrings are shared and which are not.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.