-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08-string-operations.py
More file actions
1411 lines (1097 loc) · 48.3 KB
/
08-string-operations.py
File metadata and controls
1411 lines (1097 loc) · 48.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Question: Optimize string operations for better performance in Python.
Learn and implement efficient string manipulation techniques to improve
application performance and memory usage.
Requirements:
1. Understand string concatenation performance issues
2. Learn efficient string building techniques
3. Implement string formatting optimizations
4. Use appropriate string methods for different scenarios
5. Demonstrate memory-efficient string operations
Example usage:
# Efficient string building
builder = StringBuilder()
result = builder.build_from_list(items)
# Optimized string formatting
formatter = StringFormatter()
output = formatter.format_template(template, data)
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
#
# Tips for success:
# - Read the question carefully
# - Think about string performance bottlenecks
# - Start with simple implementations
# - Test your code step by step
# - Don't worry if it's not perfect - learning is a process!
#
# Remember: The best way to learn programming is by doing, not by reading solutions!
#
# Take your time, experiment, and enjoy the learning process!
# Try to implement your solution here:
# (Write your code below this line)
# HINT SECTION (Only look if you're really stuck!)
#
# Think about:
# - Why is string concatenation with + operator slow?
# - When should you use join() vs other methods?
# - What are the benefits of f-strings vs other formatting?
# - How can you minimize string object creation?
#
# Remember: Start simple and build up complexity gradually!
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Import modules and understand string concatenation performance
# ===============================================================================
# Explanation:
# String concatenation performance is crucial in Python because strings are immutable.
# Each concatenation creates a new string object, which can be very inefficient.
import time
import sys
from typing import List, Dict, Any
from io import StringIO
def demonstrate_concatenation_performance():
"""Show the performance difference between concatenation methods."""
# Inefficient: Using + operator in a loop
def inefficient_concatenation(items: List[str]) -> str:
result = ""
for item in items:
result += item # Creates new string object each time
return result
# Efficient: Using join method
def efficient_concatenation(items: List[str]) -> str:
return "".join(items) # Single operation, much faster
# Test data
test_items = ["item" + str(i) for i in range(1000)]
# Time inefficient method
start_time = time.time()
result1 = inefficient_concatenation(test_items)
inefficient_time = time.time() - start_time
# Time efficient method
start_time = time.time()
result2 = efficient_concatenation(test_items)
efficient_time = time.time() - start_time
print(f"Inefficient concatenation time: {inefficient_time:.6f} seconds")
print(f"Efficient concatenation time: {efficient_time:.6f} seconds")
print(f"Performance improvement: {inefficient_time / efficient_time:.2f}x faster")
return result1, result2
# Step 2: Build upon Step 1 - Add StringBuilder class for efficient building
# ===============================================================================
# Explanation:
# We'll create a StringBuilder class that uses efficient methods internally
# and provides a clean interface for string building operations.
# All code from Step 1:
import time
import sys
from typing import List, Dict, Any
from io import StringIO
def demonstrate_concatenation_performance():
"""Show the performance difference between concatenation methods."""
# Inefficient: Using + operator in a loop
def inefficient_concatenation(items: List[str]) -> str:
result = ""
for item in items:
result += item # Creates new string object each time
return result
# Efficient: Using join method
def efficient_concatenation(items: List[str]) -> str:
return "".join(items) # Single operation, much faster
# Test data
test_items = ["item" + str(i) for i in range(1000)]
# Time inefficient method
start_time = time.time()
result1 = inefficient_concatenation(test_items)
inefficient_time = time.time() - start_time
# Time efficient method
start_time = time.time()
result2 = efficient_concatenation(test_items)
efficient_time = time.time() - start_time
print(f"Inefficient concatenation time: {inefficient_time:.6f} seconds")
print(f"Efficient concatenation time: {efficient_time:.6f} seconds")
print(f"Performance improvement: {inefficient_time / efficient_time:.2f}x faster")
return result1, result2
# New code for Step 2:
class StringBuilder:
"""Efficient string builder using list accumulation."""
def __init__(self):
self._parts = []
def append(self, text: str) -> 'StringBuilder':
"""Add text to the builder."""
self._parts.append(text)
return self # Enable method chaining
def append_line(self, text: str = "") -> 'StringBuilder':
"""Add text with a newline."""
self._parts.append(text + "\n")
return self
def build_from_list(self, items: List[str], separator: str = "") -> str:
"""Build string from a list of items."""
return separator.join(items)
def build(self) -> str:
"""Build the final string."""
return "".join(self._parts)
def clear(self) -> 'StringBuilder':
"""Clear the builder for reuse."""
self._parts.clear()
return self
def __len__(self) -> int:
"""Get the number of parts in the builder."""
return len(self._parts)
def demonstrate_string_builder():
"""Show StringBuilder usage and performance."""
builder = StringBuilder()
# Method chaining example
result = (builder
.append("Hello ")
.append("World")
.append_line("!")
.append("This is efficient")
.build())
print("StringBuilder result:")
print(result)
# Performance comparison
items = ["line" + str(i) for i in range(1000)]
# Using StringBuilder
start_time = time.time()
builder.clear()
for item in items:
builder.append(item)
result_builder = builder.build()
builder_time = time.time() - start_time
# Using join directly
start_time = time.time()
result_join = "".join(items)
join_time = time.time() - start_time
print(f"\nStringBuilder time: {builder_time:.6f} seconds")
print(f"Direct join time: {join_time:.6f} seconds")
print(f"StringBuilder overhead: {builder_time / join_time:.2f}x")
return result_builder, result_join
# Step 3: Build upon Steps 1-2 - Add string formatting optimizations
# ===============================================================================
# Explanation:
# String formatting performance varies significantly between different methods.
# f-strings are generally the fastest, followed by .format(), then % formatting.
# All code from Steps 1-2:
import time
import sys
from typing import List, Dict, Any
from io import StringIO
def demonstrate_concatenation_performance():
"""Show the performance difference between concatenation methods."""
# Inefficient: Using + operator in a loop
def inefficient_concatenation(items: List[str]) -> str:
result = ""
for item in items:
result += item # Creates new string object each time
return result
# Efficient: Using join method
def efficient_concatenation(items: List[str]) -> str:
return "".join(items) # Single operation, much faster
# Test data
test_items = ["item" + str(i) for i in range(1000)]
# Time inefficient method
start_time = time.time()
result1 = inefficient_concatenation(test_items)
inefficient_time = time.time() - start_time
# Time efficient method
start_time = time.time()
result2 = efficient_concatenation(test_items)
efficient_time = time.time() - start_time
print(f"Inefficient concatenation time: {inefficient_time:.6f} seconds")
print(f"Efficient concatenation time: {efficient_time:.6f} seconds")
print(f"Performance improvement: {inefficient_time / efficient_time:.2f}x faster")
return result1, result2
class StringBuilder:
"""Efficient string builder using list accumulation."""
def __init__(self):
self._parts = []
def append(self, text: str) -> 'StringBuilder':
"""Add text to the builder."""
self._parts.append(text)
return self # Enable method chaining
def append_line(self, text: str = "") -> 'StringBuilder':
"""Add text with a newline."""
self._parts.append(text + "\n")
return self
def build_from_list(self, items: List[str], separator: str = "") -> str:
"""Build string from a list of items."""
return separator.join(items)
def build(self) -> str:
"""Build the final string."""
return "".join(self._parts)
def clear(self) -> 'StringBuilder':
"""Clear the builder for reuse."""
self._parts.clear()
return self
def __len__(self) -> int:
"""Get the number of parts in the builder."""
return len(self._parts)
def demonstrate_string_builder():
"""Show StringBuilder usage and performance."""
builder = StringBuilder()
# Method chaining example
result = (builder
.append("Hello ")
.append("World")
.append_line("!")
.append("This is efficient")
.build())
print("StringBuilder result:")
print(result)
# Performance comparison
items = ["line" + str(i) for i in range(1000)]
# Using StringBuilder
start_time = time.time()
builder.clear()
for item in items:
builder.append(item)
result_builder = builder.build()
builder_time = time.time() - start_time
# Using join directly
start_time = time.time()
result_join = "".join(items)
join_time = time.time() - start_time
print(f"\nStringBuilder time: {builder_time:.6f} seconds")
print(f"Direct join time: {join_time:.6f} seconds")
print(f"StringBuilder overhead: {builder_time / join_time:.2f}x")
return result_builder, result_join
# New code for Step 3:
class StringFormatter:
"""Optimized string formatting utilities."""
@staticmethod
def compare_formatting_methods(name: str, age: int, score: float, iterations: int = 10000):
"""Compare different string formatting methods."""
# Method 1: f-strings (fastest)
start_time = time.time()
for _ in range(iterations):
result = f"Name: {name}, Age: {age}, Score: {score:.2f}"
fstring_time = time.time() - start_time
# Method 2: .format() method
start_time = time.time()
for _ in range(iterations):
result = "Name: {}, Age: {}, Score: {:.2f}".format(name, age, score)
format_time = time.time() - start_time
# Method 3: % formatting (oldest, slowest)
start_time = time.time()
for _ in range(iterations):
result = "Name: %s, Age: %d, Score: %.2f" % (name, age, score)
percent_time = time.time() - start_time
# Method 4: Template strings (safe but slower)
from string import Template
template = Template("Name: $name, Age: $age, Score: $score")
start_time = time.time()
for _ in range(iterations):
result = template.substitute(name=name, age=age, score=f"{score:.2f}")
template_time = time.time() - start_time
print(f"Formatting performance comparison ({iterations} iterations):")
print(f"f-strings: {fstring_time:.6f} seconds (baseline)")
print(f".format(): {format_time:.6f} seconds ({format_time/fstring_time:.2f}x slower)")
print(f"% formatting: {percent_time:.6f} seconds ({percent_time/fstring_time:.2f}x slower)")
print(f"Template: {template_time:.6f} seconds ({template_time/fstring_time:.2f}x slower)")
return fstring_time, format_time, percent_time, template_time
@staticmethod
def format_template(template: str, data: Dict[str, Any]) -> str:
"""Efficiently format a template with data using f-strings when possible."""
# For dynamic templates, .format() is often the best choice
return template.format(**data)
@staticmethod
def build_csv_line(values: List[Any], delimiter: str = ",") -> str:
"""Efficiently build a CSV line."""
# Convert all values to strings and join
return delimiter.join(str(value) for value in values)
@staticmethod
def build_sql_query(table: str, columns: List[str], conditions: Dict[str, Any]) -> str:
"""Build SQL query efficiently."""
# Use f-strings for static parts, join for dynamic lists
columns_str = ", ".join(columns)
where_parts = [f"{key} = '{value}'" for key, value in conditions.items()]
where_clause = " AND ".join(where_parts)
return f"SELECT {columns_str} FROM {table} WHERE {where_clause}"
def demonstrate_string_formatting():
"""Show string formatting optimizations."""
formatter = StringFormatter()
# Compare formatting methods
formatter.compare_formatting_methods("Alice", 30, 95.5)
# Template formatting
template = "Hello {name}, your score is {score} out of {total}"
data = {"name": "Bob", "score": 85, "total": 100}
result = formatter.format_template(template, data)
print(f"\nTemplate result: {result}")
# CSV building
csv_line = formatter.build_csv_line(["John", 25, 87.5, "Engineer"])
print(f"CSV line: {csv_line}")
# SQL query building
query = formatter.build_sql_query(
"users",
["name", "age", "score"],
{"department": "Engineering", "active": True}
)
print(f"SQL query: {query}")
return result, csv_line, query
# Step 4: Build upon Steps 1-3 - Add memory-efficient string operations
# ===============================================================================
# Explanation:
# Memory efficiency is crucial for large string operations. We'll explore
# techniques like StringIO, generators, and lazy evaluation.
# All code from Steps 1-3:
import time
import sys
from typing import List, Dict, Any
from io import StringIO
def demonstrate_concatenation_performance():
"""Show the performance difference between concatenation methods."""
# Inefficient: Using + operator in a loop
def inefficient_concatenation(items: List[str]) -> str:
result = ""
for item in items:
result += item # Creates new string object each time
return result
# Efficient: Using join method
def efficient_concatenation(items: List[str]) -> str:
return "".join(items) # Single operation, much faster
# Test data
test_items = ["item" + str(i) for i in range(1000)]
# Time inefficient method
start_time = time.time()
result1 = inefficient_concatenation(test_items)
inefficient_time = time.time() - start_time
# Time efficient method
start_time = time.time()
result2 = efficient_concatenation(test_items)
efficient_time = time.time() - start_time
print(f"Inefficient concatenation time: {inefficient_time:.6f} seconds")
print(f"Efficient concatenation time: {efficient_time:.6f} seconds")
print(f"Performance improvement: {inefficient_time / efficient_time:.2f}x faster")
return result1, result2
class StringBuilder:
"""Efficient string builder using list accumulation."""
def __init__(self):
self._parts = []
def append(self, text: str) -> 'StringBuilder':
"""Add text to the builder."""
self._parts.append(text)
return self # Enable method chaining
def append_line(self, text: str = "") -> 'StringBuilder':
"""Add text with a newline."""
self._parts.append(text + "\n")
return self
def build_from_list(self, items: List[str], separator: str = "") -> str:
"""Build string from a list of items."""
return separator.join(items)
def build(self) -> str:
"""Build the final string."""
return "".join(self._parts)
def clear(self) -> 'StringBuilder':
"""Clear the builder for reuse."""
self._parts.clear()
return self
def __len__(self) -> int:
"""Get the number of parts in the builder."""
return len(self._parts)
def demonstrate_string_builder():
"""Show StringBuilder usage and performance."""
builder = StringBuilder()
# Method chaining example
result = (builder
.append("Hello ")
.append("World")
.append_line("!")
.append("This is efficient")
.build())
print("StringBuilder result:")
print(result)
# Performance comparison
items = ["line" + str(i) for i in range(1000)]
# Using StringBuilder
start_time = time.time()
builder.clear()
for item in items:
builder.append(item)
result_builder = builder.build()
builder_time = time.time() - start_time
# Using join directly
start_time = time.time()
result_join = "".join(items)
join_time = time.time() - start_time
print(f"\nStringBuilder time: {builder_time:.6f} seconds")
print(f"Direct join time: {join_time:.6f} seconds")
print(f"StringBuilder overhead: {builder_time / join_time:.2f}x")
return result_builder, result_join
class StringFormatter:
"""Optimized string formatting utilities."""
@staticmethod
def compare_formatting_methods(name: str, age: int, score: float, iterations: int = 10000):
"""Compare different string formatting methods."""
# Method 1: f-strings (fastest)
start_time = time.time()
for _ in range(iterations):
result = f"Name: {name}, Age: {age}, Score: {score:.2f}"
fstring_time = time.time() - start_time
# Method 2: .format() method
start_time = time.time()
for _ in range(iterations):
result = "Name: {}, Age: {}, Score: {:.2f}".format(name, age, score)
format_time = time.time() - start_time
# Method 3: % formatting (oldest, slowest)
start_time = time.time()
for _ in range(iterations):
result = "Name: %s, Age: %d, Score: %.2f" % (name, age, score)
percent_time = time.time() - start_time
# Method 4: Template strings (safe but slower)
from string import Template
template = Template("Name: $name, Age: $age, Score: $score")
start_time = time.time()
for _ in range(iterations):
result = template.substitute(name=name, age=age, score=f"{score:.2f}")
template_time = time.time() - start_time
print(f"Formatting performance comparison ({iterations} iterations):")
print(f"f-strings: {fstring_time:.6f} seconds (baseline)")
print(f".format(): {format_time:.6f} seconds ({format_time/fstring_time:.2f}x slower)")
print(f"% formatting: {percent_time:.6f} seconds ({percent_time/fstring_time:.2f}x slower)")
print(f"Template: {template_time:.6f} seconds ({template_time/fstring_time:.2f}x slower)")
return fstring_time, format_time, percent_time, template_time
@staticmethod
def format_template(template: str, data: Dict[str, Any]) -> str:
"""Efficiently format a template with data using f-strings when possible."""
# For dynamic templates, .format() is often the best choice
return template.format(**data)
@staticmethod
def build_csv_line(values: List[Any], delimiter: str = ",") -> str:
"""Efficiently build a CSV line."""
# Convert all values to strings and join
return delimiter.join(str(value) for value in values)
@staticmethod
def build_sql_query(table: str, columns: List[str], conditions: Dict[str, Any]) -> str:
"""Build SQL query efficiently."""
# Use f-strings for static parts, join for dynamic lists
columns_str = ", ".join(columns)
where_parts = [f"{key} = '{value}'" for key, value in conditions.items()]
where_clause = " AND ".join(where_parts)
return f"SELECT {columns_str} FROM {table} WHERE {where_clause}"
def demonstrate_string_formatting():
"""Show string formatting optimizations."""
formatter = StringFormatter()
# Compare formatting methods
formatter.compare_formatting_methods("Alice", 30, 95.5)
# Template formatting
template = "Hello {name}, your score is {score} out of {total}"
data = {"name": "Bob", "score": 85, "total": 100}
result = formatter.format_template(template, data)
print(f"\nTemplate result: {result}")
# CSV building
csv_line = formatter.build_csv_line(["John", 25, 87.5, "Engineer"])
print(f"CSV line: {csv_line}")
# SQL query building
query = formatter.build_sql_query(
"users",
["name", "age", "score"],
{"department": "Engineering", "active": True}
)
print(f"SQL query: {query}")
return result, csv_line, query
# New code for Step 4:
class MemoryEfficientStringProcessor:
"""Memory-efficient string processing utilities."""
@staticmethod
def compare_memory_usage():
"""Compare memory usage of different string building methods."""
import tracemalloc
# Test data
items = [f"line{i}" for i in range(10000)]
# Method 1: String concatenation (memory inefficient)
tracemalloc.start()
result1 = ""
for item in items:
result1 += item
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
concat_memory = peak
# Method 2: Join method (memory efficient)
tracemalloc.start()
result2 = "".join(items)
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
join_memory = peak
# Method 3: StringIO (good for incremental building)
tracemalloc.start()
buffer = StringIO()
for item in items:
buffer.write(item)
result3 = buffer.getvalue()
buffer.close()
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
stringio_memory = peak
print(f"Memory usage comparison:")
print(f"String concatenation: {concat_memory / 1024 / 1024:.2f} MB")
print(f"Join method: {join_memory / 1024 / 1024:.2f} MB")
print(f"StringIO: {stringio_memory / 1024 / 1024:.2f} MB")
print(f"Join vs concat: {concat_memory / join_memory:.2f}x more memory")
return concat_memory, join_memory, stringio_memory
@staticmethod
def process_large_text_generator(lines: List[str]):
"""Process large text using generators for memory efficiency."""
def process_line(line: str) -> str:
# Simulate some processing
return line.strip().upper()
# Generator approach - processes one line at a time
for line in lines:
yield process_line(line)
@staticmethod
def build_report_with_stringio(data: List[Dict[str, Any]]) -> str:
"""Build a report using StringIO for memory efficiency."""
buffer = StringIO()
# Header
buffer.write("PERFORMANCE REPORT\n")
buffer.write("=" * 50 + "\n\n")
# Data rows
for i, record in enumerate(data, 1):
buffer.write(f"Record {i}:\n")
for key, value in record.items():
buffer.write(f" {key}: {value}\n")
buffer.write("\n")
# Footer
buffer.write(f"Total records: {len(data)}\n")
result = buffer.getvalue()
buffer.close()
return result
@staticmethod
def lazy_string_processor(text: str, chunk_size: int = 1000):
"""Process large strings lazily in chunks."""
def process_chunk(chunk: str) -> str:
# Example processing: remove extra whitespace
return " ".join(chunk.split())
# Process in chunks to avoid loading entire string in memory
for i in range(0, len(text), chunk_size):
chunk = text[i:i + chunk_size]
yield process_chunk(chunk)
@staticmethod
def efficient_string_search(text: str, patterns: List[str]) -> Dict[str, List[int]]:
"""Efficiently search for multiple patterns in text."""
results = {pattern: [] for pattern in patterns}
# Single pass through text for all patterns
for i, char in enumerate(text):
for pattern in patterns:
if text[i:].startswith(pattern):
results[pattern].append(i)
return results
def demonstrate_memory_efficiency():
"""Show memory-efficient string operations."""
processor = MemoryEfficientStringProcessor()
# Memory usage comparison
print("Memory Usage Comparison:")
processor.compare_memory_usage()
# Generator processing
print("\nGenerator Processing:")
lines = [" hello world ", " PYTHON rocks ", " efficiency matters "]
processed = list(processor.process_large_text_generator(lines))
print(f"Processed lines: {processed}")
# StringIO report building
print("\nStringIO Report Building:")
data = [
{"name": "Alice", "score": 95, "department": "Engineering"},
{"name": "Bob", "score": 87, "department": "Marketing"},
{"name": "Charlie", "score": 92, "department": "Engineering"}
]
report = processor.build_report_with_stringio(data)
print("Report preview:")
print(report[:200] + "..." if len(report) > 200 else report)
# Lazy processing
print("\nLazy String Processing:")
large_text = "This is a sample text with lots of extra spaces everywhere."
processed_chunks = list(processor.lazy_string_processor(large_text, 20))
print(f"Processed chunks: {processed_chunks}")
# Efficient search
print("\nEfficient String Search:")
search_text = "The quick brown fox jumps over the lazy dog. The fox is quick."
patterns = ["the", "fox", "quick"]
search_results = processor.efficient_string_search(search_text.lower(), patterns)
print(f"Search results: {search_results}")
return processed, report, processed_chunks, search_results
# Step 5: Build upon Steps 1-4 - Complete string operations optimization suite
# ===============================================================================
# Explanation:
# This final step combines all previous techniques into a comprehensive
# string operations optimization suite with real-world examples.
# All code from Steps 1-4:
import time
import sys
from typing import List, Dict, Any, Generator, Iterator
from io import StringIO
import re
def demonstrate_concatenation_performance():
"""Show the performance difference between concatenation methods."""
# Inefficient: Using + operator in a loop
def inefficient_concatenation(items: List[str]) -> str:
result = ""
for item in items:
result += item # Creates new string object each time
return result
# Efficient: Using join method
def efficient_concatenation(items: List[str]) -> str:
return "".join(items) # Single operation, much faster
# Test data
test_items = ["item" + str(i) for i in range(1000)]
# Time inefficient method
start_time = time.time()
result1 = inefficient_concatenation(test_items)
inefficient_time = time.time() - start_time
# Time efficient method
start_time = time.time()
result2 = efficient_concatenation(test_items)
efficient_time = time.time() - start_time
print(f"Inefficient concatenation time: {inefficient_time:.6f} seconds")
print(f"Efficient concatenation time: {efficient_time:.6f} seconds")
print(f"Performance improvement: {inefficient_time / efficient_time:.2f}x faster")
return result1, result2
class StringBuilder:
"""Efficient string builder using list accumulation."""
def __init__(self):
self._parts = []
def append(self, text: str) -> 'StringBuilder':
"""Add text to the builder."""
self._parts.append(text)
return self # Enable method chaining
def append_line(self, text: str = "") -> 'StringBuilder':
"""Add text with a newline."""
self._parts.append(text + "\n")
return self
def build_from_list(self, items: List[str], separator: str = "") -> str:
"""Build string from a list of items."""
return separator.join(items)
def build(self) -> str:
"""Build the final string."""
return "".join(self._parts)
def clear(self) -> 'StringBuilder':
"""Clear the builder for reuse."""
self._parts.clear()
return self
def __len__(self) -> int:
"""Get the number of parts in the builder."""
return len(self._parts)
def demonstrate_string_builder():
"""Show StringBuilder usage and performance."""
builder = StringBuilder()
# Method chaining example
result = (builder
.append("Hello ")
.append("World")
.append_line("!")
.append("This is efficient")
.build())
print("StringBuilder result:")
print(result)
# Performance comparison
items = ["line" + str(i) for i in range(1000)]
# Using StringBuilder
start_time = time.time()
builder.clear()
for item in items:
builder.append(item)
result_builder = builder.build()
builder_time = time.time() - start_time
# Using join directly
start_time = time.time()
result_join = "".join(items)
join_time = time.time() - start_time
print(f"\nStringBuilder time: {builder_time:.6f} seconds")
print(f"Direct join time: {join_time:.6f} seconds")
print(f"StringBuilder overhead: {builder_time / join_time:.2f}x")
return result_builder, result_join
class StringFormatter:
"""Optimized string formatting utilities."""
@staticmethod
def compare_formatting_methods(name: str, age: int, score: float, iterations: int = 10000):
"""Compare different string formatting methods."""
# Method 1: f-strings (fastest)
start_time = time.time()
for _ in range(iterations):
result = f"Name: {name}, Age: {age}, Score: {score:.2f}"
fstring_time = time.time() - start_time
# Method 2: .format() method
start_time = time.time()
for _ in range(iterations):
result = "Name: {}, Age: {}, Score: {:.2f}".format(name, age, score)
format_time = time.time() - start_time
# Method 3: % formatting (oldest, slowest)
start_time = time.time()
for _ in range(iterations):
result = "Name: %s, Age: %d, Score: %.2f" % (name, age, score)
percent_time = time.time() - start_time
# Method 4: Template strings (safe but slower)
from string import Template
template = Template("Name: $name, Age: $age, Score: $score")
start_time = time.time()
for _ in range(iterations):
result = template.substitute(name=name, age=age, score=f"{score:.2f}")
template_time = time.time() - start_time
print(f"Formatting performance comparison ({iterations} iterations):")
print(f"f-strings: {fstring_time:.6f} seconds (baseline)")
print(f".format(): {format_time:.6f} seconds ({format_time/fstring_time:.2f}x slower)")
print(f"% formatting: {percent_time:.6f} seconds ({percent_time/fstring_time:.2f}x slower)")
print(f"Template: {template_time:.6f} seconds ({template_time/fstring_time:.2f}x slower)")
return fstring_time, format_time, percent_time, template_time
@staticmethod
def format_template(template: str, data: Dict[str, Any]) -> str:
"""Efficiently format a template with data using f-strings when possible."""
# For dynamic templates, .format() is often the best choice
return template.format(**data)
@staticmethod
def build_csv_line(values: List[Any], delimiter: str = ",") -> str:
"""Efficiently build a CSV line."""
# Convert all values to strings and join
return delimiter.join(str(value) for value in values)
@staticmethod
def build_sql_query(table: str, columns: List[str], conditions: Dict[str, Any]) -> str:
"""Build SQL query efficiently."""
# Use f-strings for static parts, join for dynamic lists
columns_str = ", ".join(columns)
where_parts = [f"{key} = '{value}'" for key, value in conditions.items()]
where_clause = " AND ".join(where_parts)
return f"SELECT {columns_str} FROM {table} WHERE {where_clause}"
def demonstrate_string_formatting():
"""Show string formatting optimizations."""
formatter = StringFormatter()