Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
from timeit import timeit
def t1():
# складываем 10 строк через + из переменной
t = 'text'
for _ in range(1000):
s = t + t + t + t + t + t + t + t + t
def t2():
# склеиваем список строк через метод join
arr = ['text'] * 10
for _ in range(1000):
s = ''.join(arr)
def t3():
# складываем через + но не из переменной а непосредственно инлайн объекты
for _ in range(1000):
s = 'text' + 'text' + 'text' + ... # всего 10 раз
Теперь каждую строку склейки запустим по 10М раз
>>> timeit(t1, number=10000)
0.21951690399964718
>>> timeit(t2, number=10000)
1.4978306379998685
>>> timeit(t3, number=10000)
0.2213820789993406
Хм, а нам говорили что через "+" это плохо и медленно ))) 😁
Тут стоит учитывать, что речь идёт о склейке множества длинных строк.
Давайте изменим условия:
def t4():
t = 'text'*100
for _ in range(1000):
s = t + t + t + t + t + t + t + t + t
def t5():
arr = ['text'*100] * 10
for _ in range(1000):
s = ''.join(arr)
def t6():
for _ in range(1000):
s = 'text'*100 + 'text'*100 + ... # всего 10 раз
>>> timeit(t4, number=10000)
12.795130728000004
>>> timeit(t5, number=10000)
2.642637542999182
>>> timeit(t6, number=10000)
0.2184546610005782
Вот, уже другой разговор, сразу видна разница, в среднем в 6 раз. Но погодите, почему последний тест t6() по скорости такой же как и t3()? Ведь строки теперь в 100 раз длиннее!
Это вопросы оптимизации кода, какие простые изменения ускоряют или замедляют выполнение программы. Мы столкнулись с примером обхода обращения к переменной. Например, именно так работает директива #define в С++, во время компиляции подставляя значение переменной вместо ссылки на неё.
В Python это тоже работает, но часто ли вы сможете встретить такой способ работы со строками? К сожалению, способ почти только теоретический.
В целом, тесты показали то, что мы хотели. Делаем выводы самостоятельно.
Полный листинг 🌍
#tricks
Change in West Bengal Govt also means projects stuck now can be implemented
🔸Varanasi - Kolkata Expressway
🔸Gorakhpur - Siliguri Expressway
🔸Extension of Eastern Dedicated Freight Corridor from Bihar to Bengal
🔸Varanasi - Siliguri High Speed Rail Corridor will also see timely execution
#Infra
India's toll plazas gets a serious upgrade.
The Multi-Lane Free Flow (MLFF) system is now live and aim is to eventually transition to no boom barriers, no queues, no stopping with FASTag deducted automatically.
108 toll plazas across major national highways, with full rollout targeting all four-lane+ corridors by 2029. The end goal is to eliminate human intervention, no revenue leakage, no fuel wasted idling at barriers.
#Infra
Mumbai-Ahmedabad Bullet Train Project: Assembly of India's largest-ever Tunnel Boring Machine (TBM), with a diameter of 13.56 meters, progressing at Shaft 2 in Vikhroli, Mumbai. Drilling is expected to begin in July 2026. #Infra
PM Modi to inaugurate the 594 km long Ganga Expressway on April 29
India's longest expressway, linking Meerut-Prayagraj via 12 districts, cutting travel time by ~50% and boosting connectivity & trade
#Infra
Not just sea bridges, coastal roads, tunnels, and metros. In housing too, Mumbai is being rebuilt from the ground up.
Dharavi: 641 acres, ₹95,700 crore.
Motilal Nagar in Goregaon: 143 acres, up to ₹1,00,000 crore.
BDD Chawls in Worli: 87 acres with Tata, Capacit'e and CITIC group.
Bhendi Bazaar
Kamathipura
5 landmark redevelopment projects with Adani, Tata, and marquee developers. Combined investment crossing ₹2,00,000 crore.
The city that powers India's economy is finally getting the urban infrastructure its ambition always deserved #Infra
Zoji La Tunnel Nears a Major Breakthrough
India’s strategic Zoji La tunnel connecting Kashmir to Ladakh is on the brink of a breakthrough, with the final blast expected by end of May 2026. Only 300 meters remain of the 13.1 km tunnel, with work progressing from both Sonamarg and Minamarg ends. #Infra
Infrastructure spending in India has grown six-fold to more than ₹12 lakh crore a year since 2014, compared with less than ₹2 lakh crore before 2014, Prime Minister Narendra Modi said on Tuesday. #Infra
Bogibeel Bridge (4.94 km) built on the mighty Brahmaputra river cuts Dibrugarh–Itanagar road distance by 150 km and rail by 705 km. Project cost revised to ₹4,857 crore from ₹3,230 crore; inaugurated in 2018 after 2002 start. Double-line rail + 3-lane road link boosts connectivity across Assam–Arunachal. #Infra