Why the memory of String class is so big?

20 visualizzazioni (ultimi 30 giorni)
ql sang
ql sang il 8 Lug 2019
Commentato: Jan il 9 Lug 2019
>> a = ""
a =
""
>> whos a
Name Size Bytes Class Attributes
a 1x1 134 string
As the code above shows, it still has 134bytes of memory, even if I don't enter any characters. I understand that this may be a trade secret of MATLAB (just like the built-in function), but I don't quite understand why it takes up so much space.
I'm just a beginner. The official documentation says that starting with R2017a, you can create strings using double quotes. I would like to ask senior, what is his biggest advantage over the past?
  1 Commento
Stephen23
Stephen23 il 8 Lug 2019
Modificato: Stephen23 il 9 Lug 2019
"I don't quite understand why it takes up so much space"
"what is his biggest advantage over the past?"
String arrays of the same size as corresponding numeric arrays.

Accedi per commentare.

Risposta accettata

Guillaume
Guillaume il 8 Lug 2019
Can't tell you why the overhead. On my computer (R2019a) it looks like it's 158 bytes. However, it's certainly not something to worry about. Note that matlab lies to you when it tells you that an empty char array takes 0 bytes. There is also some overhead.
The benefit of the string class over char arrays is a more modern and logical interface.
  • Want to store an array of string, just use standard matrix indexing, arr(1) is your first string, etc. As an array of char, either use a 2D char array, arr(1, :) and accept some strings need to be padded or use a cell array of char vector, arr{1}.
  • Want to compare strings, simply use ==. Beginners often try to use == with char arrays, which will either error or not return the expected result. You have to use strcmp.
  • string composition is a lot more intuitive as well:
mystring = "The answer is " + 42 + ". Now what was the question?"
vs
mycharvector = ['The answer is ', num2str(42), '.Now what was the question']
There are probably other benefits that I forget. But to me, the principle advantage is that they behave similar to strings in other modern high-level languages (such as python, C++, C#, etc.) whereas cell array char vectors is more akin to the old style C programming.
Next, I'm hoping that Mathworks will overhaul their IO mechanism to move it into this this centuy and have everything based on streams.
  3 Commenti
Guillaume
Guillaume il 9 Lug 2019
A well implemented stream interface shouldn't have too much overhead, and streaming directly from memory/network would be a lot faster than going through a temporary file.
Jan
Jan il 9 Lug 2019
I'd be glad already, if the string objects are terminated by \0, such that I can use them directly in C-Mex functions or for calling libraries of the operating system.

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by