Greetings to everybody!
As far as I know a string needs as much memory as many character it contains.
Opposing this theory I have two - theoretically equivalent - ways of building a string, but the storage space seems to be very different. Here is the code:
Code:
class Program
{
static void Main(string[] args)
{
A a = new A();
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
bf.Serialize(fs, a);
fs.Close();
}
}
[Serializable]
class A
{
List<string> aha;
public List<string> Aha
{
get { return aha; }
}
public A()
{
aha = new List<string>();
for (int i = 0; i < 10000; i++)
{
aha.Add("a9999b");
}
}
}
and the other version:
Code:
class Program
{
static void Main(string[] args)
{
A a = new A();
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
bf.Serialize(fs, a);
fs.Close();
}
}
[Serializable]
class A
{
List<string> aha;
public List<string> Aha
{
get { return aha; }
}
public A()
{
aha = new List<string>();
for (int i = 0; i < 10000; i++)
{
aha.Add("a" + i.ToString() + "b");
}
}
}
The only difference is the way the string is built, and all the strings in the first version are non-longer than the ones in the second, so I thought that file will occupy less bytes. But surprisingly the first file's size is 50kB and the second's is 117kB.
Could You tell me what's wrong? Are my starting hypothesys' wrong or is this normal, and if not how should the second solution occupy the same amount of memory (or less, as it's strings are shorter?)?
Thank You in advance!
Vik