{ "cells": [ { "cell_type": "markdown", "id": "16b134de-8c9f-4c21-8ef9-8d4121fb7c67", "metadata": {}, "source": [ "\n", "### Preallocating arrays vs push in julia" ] }, { "cell_type": "code", "execution_count": null, "id": "10827d90-8f2b-4064-b6c7-c8553c851b37", "metadata": {}, "outputs": [], "source": [ "] add BenchmarkTools" ] }, { "cell_type": "code", "execution_count": null, "id": "a71fc89d-fece-4758-9c26-d2be649d928b", "metadata": {}, "outputs": [], "source": [ "\n", "using BenchmarkTools" ] }, { "cell_type": "markdown", "id": "612d79ec-6ec7-4eea-b8bd-dc8136e59ddb", "metadata": {}, "source": [ "\n", "Allocate array of a fixed length and store the elements as they are calculated" ] }, { "cell_type": "code", "execution_count": null, "id": "c94681aa-b8f8-4c6c-8095-3972c566458e", "metadata": {}, "outputs": [], "source": [ "\n", "function init1(n)\n", " x = zeros(n)\n", " for i = 1:n\n", " x[i] = i/2\n", " end\n", " return x\n", "end" ] }, { "cell_type": "markdown", "id": "08e0dd34-fbfc-4afe-89c4-b43a2867c294", "metadata": {}, "source": [ "\n", "Create a zero-length array and expand it as new element need to be stored" ] }, { "cell_type": "code", "execution_count": null, "id": "e772ceb6-6b16-4c05-ab3d-064d1e47ee71", "metadata": {}, "outputs": [], "source": [ "\n", "function init2(n)\n", " x = []\n", " for i = 1:n\n", " push!(x, i/2)\n", " end\n", " return x\n", "end" ] }, { "cell_type": "code", "execution_count": null, "id": "f8b8d84e-3ba8-40a3-a8be-3494d79bbc83", "metadata": {}, "outputs": [], "source": [ "\n", "x1 = init1(100)\n", "x2 = init2(100);" ] }, { "cell_type": "code", "execution_count": null, "id": "7ce6efe4-25e0-4be2-80fe-5e6ba1bdccbd", "metadata": {}, "outputs": [], "source": [ "\n", "\n", "x1 == x2" ] }, { "cell_type": "code", "execution_count": null, "id": "88c606c3-9f0d-4bcc-931c-51bfa132e96f", "metadata": {}, "outputs": [], "source": [ "\n", "@btime init1(100);" ] }, { "cell_type": "code", "execution_count": null, "id": "1838e095-128c-468a-b643-59ede475d8ba", "metadata": {}, "outputs": [], "source": [ "\n", "@btime init2(100);" ] }, { "cell_type": "code", "execution_count": null, "id": "4feff9b3-6c4a-4141-8ffd-e6b81434f0fe", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Julia 1.11.6", "language": "julia", "name": "julia-1.11" }, "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.11.6" } }, "nbformat": 4, "nbformat_minor": 5 }