字符串拼接效率
styleguide | Style guides for Google-originated open-source projects https://google.github.io/styleguide/pyguide.html
def now():
print(datetime.datetime.now())
now()
f = io.StringIO('')
for i in range(1000000):
f.write(s)
a = f.getvalue()
now()
now()
s0 = ''
for i in range(1000000):
s0 += s
s1 = s0
now()
now()
l = []
for i in range(1000000):
l.append(s)
s2 = ''.join(l)
now()
StringIO和BytesIO - 廖雪峰的官方网站 https://www.liaoxuefeng.com/wiki/1016959663602400/1017609424203904
StringIO
很多时候,数据读写不一定是文件,也可以在内存中读写。
StringIO顾名思义就是在内存中读写str。
要把str写入StringIO,我们需要先创建一个StringIO,然后,像文件一样写入即可:
>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue())
hello world!
getvalue()
方法用于获得写入后的str。
要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取:
>>> from io import StringIO
>>> f = StringIO('Hello!\nHi!\nGoodbye!')
>>> while True:
... s = f.readline()
... if s == '':
... break
... print(s.strip())
...
Hello!
Hi!
Goodbye!
BytesIO
StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。
BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:
>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
请注意,写入的不是str,而是经过UTF-8编码的bytes。
和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取:
>>> from io import BytesIO >>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87') >>> f.read() b'\xe4\xb8\xad\xe6\x96\x87'
3.10 Strings
Use an f-string, the %
operator, or the format
method for formatting strings, even when the parameters are all strings. Use your best judgment to decide between string formatting options. A single join with +
is okay but do not format with +
.
Yes: x = f'name: {name}; score: {n}'
x = '%s, %s!' % (imperative, expletive)
x = '{}, {}'.format(first, second)
x = 'name: %s; score: %d' % (name, n)
x = 'name: %(name)s; score: %(score)d' % {'name':name, 'score':n}
x = 'name: {}; score: {}'.format(name, n)
x = a + b
No: x = first + ', ' + second
x = 'name: ' + name + '; score: ' + str(n)
Avoid using the +
and +=
operators to accumulate a string within a loop. In some conditions, accumulating a string with addition can lead to quadratic rather than linear running time. Although common accumulations of this sort may be optimized on CPython, that is an implementation detail. The conditions under which an optimization applies are not easy to predict and may change. Instead, add each substring to a list and ''.join
the list after the loop terminates, or write each substring to an io.StringIO
buffer. These techniques consistently have amortized-linear run-time complexity.
Yes: items = ['<table>']
for last_name, first_name in employee_list:
items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
items.append('</table>')
employee_table = ''.join(items)
No: employee_table = '<table>'
for last_name, first_name in employee_list:
employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
employee_table += '</table>'
Different ways to concatenate two strings in Golang - GeeksforGeeks https://www.geeksforgeeks.org/different-ways-to-concatenate-two-strings-in-golang/
Golang拼接字符串的5种方法及其效率_Chrispink-CSDN博客_golang 字符串拼接效率 https://blog.csdn.net/m0_37422289/article/details/103362740
var buf bytes.Buffer
buf.WriteString(r)
buf.WriteString(s)
f := func(s string) string {
fmt.Println("START--", n())
r := s
for i := 0; i < 10241024; i++ {
r += s
}
fmt.Println("END--", n())
return r
}