python sql拼接StringBuilder_字符串

Photo from Unsplash

python sql拼接StringBuilder_字符串_02

在编码过程中,我们经常需要对字符串进行连接处理操作。如果我们能使用优雅的方式来处理字符串连接,那么程序内存开销会小很多。

众所周知,在 Java 语言中使用运算符 "+" 来连接字符串效率是最低。因为 String 类是 final 类型,使用 "+" 连接字符串时,内部是创建临时对象 StringBuffer,再转化为 String。

那么在 Python 中,使用 "+" 连接字符串同样也是效率最低的吗? 让我们来做个测试验证下。在做测试之前, 我们先了解下 Python 中几种连接字符串的方法。

1、使用 "+" 运算符连接

这种方式是最容易想到连接方式。

fir = 'hello,'
sec = 'monkey'
print(fir + sec)

 2、使用 "%" 运算符连接

这种方式有点像 C 语言中 printf 函数的功能,使用 "%s" 来表示字符串类型参数,再用 "%" 连接一个字符串和一组变量。

fir = 'hello'
sec = 'monkey'
result = '%s, %s' % (fir, sec)
print(result)

上述代码是用元组作为变量,"%" 还支持字典类型作为变量。

fir = 'hello'
sec = 'monkey'
result = '%(fir)s, %(sec)s' % {'fir':fir, 'sec':sec}
print(result)

3、使用 format() 格式化连接

这种格式化字符串函数是 Python 特有的,属于高级用法。因为它威力强大,不仅支持多种参数类型,还支持对数字格式化。

fir = 'hello'
sec = 'monkey'
result = '{}, {}'.format(fir, sec)
print(result)

上述代码使用隐式的位置参数,format() 还能显式指定参数所对应变量的位置。

fir = 'hello'
sec = 'monkey'
result = '{1}, {0}'.format(fir, sec)
print(result)

4、使用 join() 方式

这种算是技巧性办法。join() 方法通常是用于连接列表或元组中的元素。

list = ['1', '2', '3']
result = '+'.join(list)
print(result)

运行结果:

1+2+3

接下来,我使用 cProfile 来分析这种连接字符串所消耗的时间。cProfile 输出的结果是以秒为单位,而短字符串连接时间太短,输出结果都是 0.000 秒。所以我将字符串分别乘以 100000 变成长字符串。这样方便我们更加直观地观察结果。 

join() 这种连接方式是比较特殊,所以不将其列入测试范围。

以下是测试代码:

# -*- coding:utf-8 -*-
import cProfile

# 使用 "+" 运算符连接
def concat_way1():
    fir = 'Hello' * 1000000
    sec = '极客猴' * 1000000
    result = fir + sec

# 使用 "%" 运算符连接
def concat_way2():
    fir = 'Hello' * 1000000
    sec = '极客猴' * 1000000
    result = '%s%s' % (fir, sec)

# 使用 format() 格式化连接, 隐藏参数位置
def concat_way3():
    str1 = 'Hello' * 1000000
    sec = '极客猴' * 1000000
    result = '{}{}'.format(str1, sec)

# 使用 format() 格式化连接, 指定参数位置
def concat_way4():
    fir = 'Hello' * 1000000
    sec = '极客猴' * 1000000
    result = '{0}{1}'.format(fir, sec)

if __name__ == '__main__':
    cProfile.run('concat_way1()')
    cProfile.run('concat_way2()')
    cProfile.run('concat_way3()')
    cProfile.run('concat_way4()')

最后 cProfile 统计结果是:

python sql拼接StringBuilder_极客_03

从结果上看,跟我们设想的不太一样,有点出乎我们的意料。使用操作符 "+" 连接字符串竟然耗时最少,其次是使用隐式参数的 format() 方式,耗时最长的是使用 "%" 符号。