Performance
NAME
Inline::Python3::Performance - Performance optimization guide and utilities
DESCRIPTION
This module provides performance optimization techniques and utilities for Inline::Python3.
PERFORMANCE TIPS
1. Use Lazy Evaluation
Don't force conversion of large data structures unless necessary:
# Bad - forces immediate conversion
my @data = $py.call('make_large_list', 10000).raku-value;
# Good - lazy evaluation
my $data = $py.call('make_large_list', 10000);
my $first = $data.raku-value[0]; # Only converts what's needed
2. Cache Python Objects
Reuse Python objects instead of recreating them:
# Bad - creates object every time
for ^1000 {
my $obj = $py.call('MyClass');
$obj.process($data);
}
# Good - reuse object
my $obj = $py.call('MyClass');
for ^1000 {
$obj.process($data);
}
3. Batch Operations
Process data in batches:
# Bad - many individual calls
my @results;
for @data -> $item {
@results.push: $py.call('process', $item);
}
# Good - single batch call
my @results = $py.call('process_batch', @data);
4. Use Native Python Loops
For heavy computation, use Python's native loops:
# Bad - Raku loop calling Python
my $sum = 0;
for @data -> $x {
$sum += $py.call('compute', $x);
}
# Good - Python does the loop
$py.run(q:to/PYTHON/);
def compute_all(data):
return sum(compute(x) for x in data)
PYTHON
my $sum = $py.call('compute_all', @data);
5. Minimize Type Conversions
Keep data in Python when doing multiple operations:
# Bad - converts back and forth
my @data = $py.call('load_data');
@data = @data.map(* * 2);
my $result = $py.call('process', @data);
# Good - stay in Python
$py.run(q:to/PYTHON/);
data = load_data()
data = [x * 2 for x in data]
result = process(data)
PYTHON
my $result = $py.run('result', :eval);