我之前偶然发现了这个文档。它评估了Python中几种字符串连接方法的性能。以下是其中比较的6种方法中的4种:
Python字符串连接方法
方法1:朴素的追加
def method1():
out_str = ''
for num in xrange(loop_count):
out_str += `num`
return out_str
方法四:构建字符串列表,然后连接它们
def method4():
str_list = []
for num in xrange(loop_count):
str_list.append(`num`)
return ''.join(str_list)
Method 5: Write to a pseudo file
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)])
根据结果得出以下结论:
大多数实际程序中我会使用方法6。它快速且易于理解。但需要你能够编写单个表达式来返回每个要追加的值。有时这种方式并不方便,例如当有几个不同的代码块正在生成输出时。在这些情况下,可以在方法4和方法5之间选择。
阅读本文后,我意识到自己并不知道5和6两种方法。大多数情况下,我现在更喜欢使用方法5,因为它允许我像写文件一样写字符串。
我的问题是,matlab中的字符串连接有哪些不同的技术?我几乎不在matlab中处理字符串,但我遇到了一个需要我写字符串的问题。一种解决方案我想到的是写入临时文件,并在完成后读取该文件。但在这样做之前,我决定先问一下是否有更好的选项。现在,这里有一种天真的matlab追加方法:
Matlab 字符串连接方法
方法1:天真的追加
function out_str = method1(loop_count)
out_str = '';
for num=1:loop_count
out_str = [out_str num2str(num)]; %#ok<AGROW>
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.
method1
实现可能因为使用了num2str
而受到很大影响,尝试使用sprintf('%d', num)
替代它。将数字转换为字符串与字符串连接分开处理可以获得更可靠的结果。 - erikcedsprintf
,那么method1
比method2
更快。 - jmlopez