Skip to content

Instantly share code, notes, and snippets.

@lerno
Last active February 16, 2024 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lerno/36c6d404da3a8221915dee68ec521bb7 to your computer and use it in GitHub Desktop.
Save lerno/36c6d404da3a8221915dee68ec521bb7 to your computer and use it in GitHub Desktop.
import std::io;
import std::collections::list;
define DoubleList = List<double>;
fn double test_list_on_heap(int len)
{
DoubleList list; // By default will allocate on the heap
defer list.free(); // Free at end
for (int i = 0; i < len; i++)
{
list.push(i + 1.0);
}
double sum = 0;
foreach (d : list) sum += d;
return sum;
}
fn double test_list_on_temp_allocator(int len)
{
DoubleList list;
@pool()
{
list.temp_init(); // Temp init
for (int i = 0; i < len; i++)
{
list.push(i + 1.0);
}
double sum = 0;
foreach (d : list) sum += d;
// No need to free explicitly
return sum;
};
}
fn double test_array_on_heap(int len)
{
double[] arr = mem::alloc_array(double, len);
defer mem::free(arr); // Free at end.
for (int i = 0; i < len; i++)
{
arr[i] = i + 1.0;
}
double sum = 0;
foreach (d : arr) sum += d;
return sum;
}
fn double test_array_on_temp_allocator(int len)
{
@pool()
{
double[] arr = array::talloc_array(double, len); // Released when exiting `pool()`
for (int i = 0; i < len; i++)
{
arr[i] = i + 1.0;
}
double sum = 0;
foreach (d : arr) sum += d;
return sum;
};
}
fn void main()
{
io::printfn("Sum 1-10: %d", test_list_on_heap(10));
io::printfn("Sum 1-10: %d", test_list_on_temp_allocator(10));
io::printfn("Sum 1-10: %d", test_array_on_heap(10));
io::printfn("Sum 1-10: %d", test_array_on_temp_allocator(10));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment