Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Indian Railways has officially issued the Gazette Notification for operationalizing the new South Coast Railway Zone.
🔹 Divisions included:
• Visakhapatnam
• Vijayawada
• Guntur
• Guntakal
#Railways
South Central #Railways seeks ~1,125 acres in Telangana for 4 mega coaching terminals around Hyderabad—sites at Dabilpur (250 acres), Nagulapalli (325), Jukkal (300) and Cherlapalli expansion (250). Plan aims to decongest Secunderabad/Hyderabad/Kacheguda hubs.
Indian Railways Approves ₹895.30 Crore Projects for Power System Upgradation and Bridge Infrastructure
₹671.72 Cr Kolkata Metro Upgrade with 7 New Traction Substations and Power System Augmentation from 11KV to 33 KV for Higher Frequency & Capacity Expansion
Approvals to Pave Way for 2.5-Minute Metro Headway Upgrade from Existing 5-Minute Operations, Boosting Line Capacity to Meet Rising Passenger Demand
₹223.58 Cr Adra Bridge Project to Strengthen Critical Freight Route and Industrial Connectivity
#Railways
«Узтемирйулконтейнер» преобразовался в «Темирйулкарго»🇺🇿🚆
Не только новое название, но и новые услуги:
• по управлению грузоперевозками «от двери до двери»
• по формированию логистических центров и терминалов
• по созданию логистических цепочек поставок грузов с функцией оперирования мультимодальными логистическими терминалами за рубежом
Очень интересно, что из этого получится🚂
#UZBEKISTAN#RAILWAYS
Sikkim’s first railway station Rangpo Terminal takes shape on the Sivok Rangpo line 🚄🇮🇳
▪️ B+G+5 with local Architecture on 16.5 acres
▪️ Cost : ₹335+ Cr
▪️ Promoter : Northeast Frontier Railway Division
▪️ Contractor : IRCON International Limited
▪️ Status : Under Construction
#Railways#Infra
Railways has set a target to complete the Detailed Project Reports (DPRs) for three bullet train corridors by March 2027. These include the Hyderabad-Chennai, Hyderabad-Bengaluru and Patna-Siliguri.
#Railways#Infra
#Railways Minister Ashwini Vaishnaw inaugurates Aditya, BEML’s self reliant high speed bullet train plant in Bengaluru 🚄🇮🇳
The facility will build indigenous B28 trains and future B35 next gen sets, boosting Bharat’s push for advanced, homegrown high speed rail. #aatmarnirbharbharat
Ashvini Vaishnaw:
India’s Aatmanirbhar bullet train B28 is being developed with manufacturing at BEML’s Aditya plant equipped with advanced, high precision machines, including robotic laser welding systems. 🚄🇮🇳
🇮🇳🤝🇧🇩 Bangladesh is moving ahead with a significant upgrade of its railway network, with plans to procure 200 broad-gauge passenger coaches from India in a deal to strengthen capacity and improve services across key routes.
#Railways Minister Shaikh Rabiul Alam informed Parliament that deliveries are scheduled to begin in 2026 and will continue in phases until December 2027 #Exports
https://swarajyamag.com/news-brief/bangladesh-to-induct-200-indian-broad-gauge-coaches-by-2027-signals-wider-fleet-expansion
Indian #Railways is delivering transformation at scale: 55,000 km of track renewed since 2014, 90% fewer rail failures, and track running at 110 kmph+ has risen from 40% to 80%. 🛤🚉
Indian Railways carries 25,000+ trains and 20 million+ passengers daily. Over 80,000 km of stronger rail network, 44,000 km of upgraded sleepers, and 8,00,000 machine-hours logged.
When the backbone improves, the impact multiplies across safety, punctuality, logistics, and productivity. That is nation-building in motion. #Reforms#Infra