Perl is really good for writing the kind of string/file parsing programs that I usually need to do. What I really love is the insignificant amount of time it takes me to write quick scripts and throwaway code, compared to C/C++/JAVA. However, I want to learn how to speed things up.
For example, I would want to learn how to give hints to Perl so that it can make some decisions better—especially things related to strings. It seems to me that Perl copies a string whenever you do anything regardless of whether you really modify the copy later or not. Is this by design (and can I turn that away using some magic?) or am I ranting?
I really want to treat some strings as (const char *). I am sure we always do not need everything to be a std::string with all its baggage involved (let’s assume std::string to be analogous to Perl string). Can I give a hint to Perl to do that on some strings?
I remember reading in some article (please comment if you can place it) that you can hint to Perl that you will not modify some variable and thus it removes the extra baggage that is otherwise required if you were to modify it, etc.
I believe Perl variables have two internal pointers to a same Perl variable—one can store a number and another a string (array of characters). Could I always tell Perl to choose one throughout? Could I make Perl treat some strings as (const char *) so that they do not tag around functionality required to modify them?
For example, I read somewhere (maybe the same article?) that unpack() is faster than substr() because substr() returns a lvalue, so that you can operate on it as well. For example, if I wanted to replace the first two characters of a string with ‘ef’, I could write:
substr(string, 0, 2) = 'ef'; # string now begins with 'ef'
Hence, unless I am using this special feature of substr(), am I better off using substr?
Did I just rant all the way through?
You can set the
SvREADONLYflag on a variable withReadonly::XS, but that does not improve the efficiency. Efficiency comes from choosing the right algorithm, not through compiler hints. If you want your code to be faster/use less memory then profile it (seeDevel::NYTProf). When you find a bottleneck either use a different algorithm there or switch to useXS.Also, if you are going to try to optimize something, make sure the result really is faster, here is substr vs unpack:
Here is the benchmark code.