不久前我偶然发现了这个document。它评估了python中几种连接方法的性能。以下是它比较的6种方法中的4种:
Python字符串连接方法
方法一:天真附加def method1():
out_str = ''
for num in xrange(loop_count):
out_str += `num`
return out_str
方法4:建立一个字符串列表,然后将其连接到
^{pr2}$
方法5:写入伪文件def method5():
from cStringIO import StringIO
file_str = StringIO()
for num in xrange(loop_count):
file_str.write(`num`)
return file_str.getvalue()
方法6:列出理解def method6():
return ''.join([`num` for num in xrange(loop_count)])
结果得出如下结论:I would use Method 6 in most real programs. It's fast and it's easy to understand. It does require that you be able to write a single expression that returns each of the values to append. Sometimes that's just not convenient to do - for example when there are several different chunks of code that are generating output. In those cases you can pick between Method 4 and Method 5.
读完这篇文章后,我意识到我不知道方法5和方法6。在大多数情况下,我现在更喜欢使用方法5,因为它允许我以与写入文件相同的方式写入字符串。在
我的问题是,在matlab中,字符串连接有哪些不同的技术?我在matlab中很少处理字符串,但是我遇到了一个需要我编写字符串的问题。我想到的一个解决方案是写入一个临时文件,并在完成后读取该文件。但在做这件事之前,我决定问问是否有更好的选择。下面是matlab中一个简单的附加方法:
Matlab字符串连接方法
方法一:天真附加function out_str = method1(loop_count)
out_str = '';
for num=1:loop_count
out_str = [out_str num2str(num)]; %#ok
end
end
Matlab中是否有与方法4、5和6类似的方法可以用于效率比较?在
编辑:
下面是一些类似于python中方法5的方法(写入文件):function out_str = method2(loop_count)
fid = fopen('._tmpfile.tmp', 'w');
for num=1:loop_count
fprintf(fid, '%d', num);
end
fclose(fid);
out_str = fileread('._tmpfile.tmp');
end
这是一个简单的测试:>> tic; tmp1 = method1(100000); toc
Elapsed time is 13.144053 seconds.
>> tic; tmp2 = method2(100000); toc
Elapsed time is 2.358082 seconds.