Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
💫Библиотека Chanel в Шанхае: 50 000 вариантов внеклассного чтения по искусству #architecture
В ноябре прошлого года Дом моды Chanel открыл первую публичную библиотеку современного искусства в Шанхае.
Пространство расположено на третьем этаже музея Power Station of Art. Проект является частью долгосрочного партнерства музея, бренда и программы Next Cultural Producer, которая занимается поддержкой современных китайских ремесел и искусства.
Помимо книг и аудиоматериалов, в библиотеке будут размещать работы китайских авторов, дизайн-проекты и инсталляции.
Открытие библиотеки подкрепило тенденцию масштабных партнерств моды и искусства — все чаще бренды развивают проекты, направленные на поддержку арт-индустрии.
📎Если вам интересен не только зарубежный, но и российский арт-рынок, то узнать о восприятии и динамике развития мира современного искусства в России в 2025 году можно по ссылке в нашем исследовании ArtLuch.
ART FLASH
photo of a 50m high wave tsunami about to hit a small island with a Small mansion on it, close to the house --ar 9:16 --v 7
by atypicalplayer
#architecture
📣Midjourney prompts
A gigantic megastructure space station in the shape of an electric bridge, hovering above the Martian surface, photographed from ground level. Published in National Geographic magazine, 2057. 3D render, 8mm lens, Kodak film stock --ar 105:128 --v 7
/ bridge turn
by atakan5698
#architecture
📣Midjourney prompts
A highly realistic image of a storefront in a Texas landscape, featuring a wide-angle view from the street. The store has a large glass display window showcasing items like frying pans, pillows, kettles, and mugs. Above the entrance, there is a bold sign that reads ‘Household Gunshop.’ The setting is sunny and dusty, with a typical Texan small-town atmosphere. The focus is on the realism of the scene, emphasizing the reflections and details in the glass and the store’s unique character --ar 16:9 --v 6.1
by besspalovalina
#architecture
📣 Midjourney prompts
the golden gate bridge lit up at night with christmas lights. there is a person at the bottom of the frame, close to the camera that is connecting an extension cord in front of them to turn on the lights --v 6.1 --ar 4:5
by jlange51
#architecture
📣 Midjourney prompts
A minimalist building facade made of beige brick with large wooden windows and a brown door, featuring intricate geometric patterns on the wall, straight lines, and modern architecture. This image is an example of architectural photography, as seen on Archdaily. --ar 85:128 --q 2 --v 6.1
by _solncev
#architecture
🔱 Prompt collection
front view of an adobe beehive shaped building made from salt crystals with round windows, in the desert at dusk, illuminated by lights inside --v 6.1
by hadjaa__
#architecture
🔱 Prompt collection
🔥Собрал для вас целую корзинку свежих промптов🔥
the broken circular baroque building's cut-offs floating in the air --v 6.0
by negseungeimjeu06
#architecture
🐝 Prompt collection
A cinematic photograph capturing fragments of French classical architecture suspended in mid-air, bathed in the glow of orange laser beams. The dense mist envelops the scene, adding a layer of mystery to the timeless elegance of the floating ruins. Created Using: high dynamic range imaging, photorealistic textures of marble and ornate carvings, dynamic floating debris, atmospheric fog effects, futuristic lighting, enhanced contrast, dramatic mood, surreal juxtaposition of history and modernity --v 6 --ar 4:5
by doojiang
#architecture
🐝 Prompt collection
a shell shaped biophilic cabin with camouflaged roof, built seamlessly into the dune landscape of portugal, in the style of naturalistic compositions, sustainable architecture, rectangular design, covered in vegetation, blends in with the surrounding nature, green roof, minimalist sets, fujifilm pro --ar 4:5 --style raw --v 6.0
by mesutyucel
#architecture
🐝 Prompt collection
A solitary person standing in front of the illuminated Colosseum in Rome, with a giant, glowing moon in the sky, its light casting shadows through the ancient arches, highlighting the grandeur of the historical monument. --ar 51:64 --v 6.0 --style raw
-
An individual alone at the base of the towering Mount Fuji, illuminated by a massive, glowing moon, creating an impressive contrast between the serene figure and the majestic, snow-capped peak of Japan. --ar 51:64 --v 6.0 --style raw
-
A solitary person standing in front of the illuminated Eiffel Tower at night, with a giant, detailed moon hanging low in the sky, its light reflecting off the Seine River, highlighting the majesty of Paris --ar 51:64 --v 6.0 --style raw
by jose20239
#architecture
🍄 Prompt collection