Always prefer vectorized operations over JavaScript loops. numpy-ts operations run on typed arrays with optimized internal loops, avoiding the overhead of JavaScript function calls and dynamic type checks.
Avoiding unnecessary copies (use views when possible)
Views share the same underlying data buffer as the original array. Operations that return views are effectively free — no memory allocation and no data copying.
When reducing along an axis, the reduced dimension disappears by default. Use keepdims: true to preserve it as a size-1 dimension, which makes subsequent broadcasting operations work without manual reshaping.
{"docsConfig":{"theme":"mint","$schema":"https://mintlify.com/docs.json","name":"numpy-ts","description":"Complete NumPy implementation for TypeScript and JavaScript","colors":{"primary":"#3179C7","light":"#3179C7","dark":"#3179C7"},"logo":{"light":"https://mintcdn.com/none-4568e96a/TklIwzPdQ8Sv_cxD/images/logo-light.svg?fit=max\u0026auto=format\u0026n=TklIwzPdQ8Sv_cxD\u0026q=85\u0026s=85a09d3e9971808ec73bf6e2eddcb989","dark":"https://mintcdn.com/none-4568e96a/TklIwzPdQ8Sv_cxD/images/logo-dark.svg?fit=max\u0026auto=format\u0026n=TklIwzPdQ8Sv_cxD\u0026q=85\u0026s=57584fb2637b84d53a79c187e3242f72"},"favicon":"https://mintcdn.com/none-4568e96a/TklIwzPdQ8Sv_cxD/images/favicon.svg?fit=max\u0026auto=format\u0026n=TklIwzPdQ8Sv_cxD\u0026q=85\u0026s=1a1b3c01a14ea06742777b11c71d0a7e","navbar":{"links":[{"href":"https://github.com/dupontcyborg/numpy-ts","type":"github"}]},"footer":{"socials":{"github":"https://github.com/dupontcyborg/numpy-ts","linkedin":"https://linkedin.com/in/cyborgnico","earth-americas":"https://www.cyborg.co/?ref=numpyts.dev"}},"seo":{"metatags":{"canonical":"https://numpyts.dev"}},"integrations":{"plausible":{"domain":"numpyts.dev","server":"d1w0psmo3bkh8z.cloudfront.net"}},"contextual":{"options":["copy","view","chatgpt","claude","cursor","vscode"],"display":"header"},"styling":{"latex":true},"navigation":{"pages":[]}},"deployment":{"deploymentMetadataValue":{"subdomain":"none-4568e96a","hasAudioNarration":false,"actualSubdomain":"none-4568e96a","customDomains":["numpyts.dev"],"gitSource":{"type":"github","owner":"dupontcyborg","repo":"numpy-ts","deployBranch":"main","contentDirectory":"docs","isPrivate":true,"mountPath":"","label":""},"chroma":{"liveDeploymentHistoryId":"6a9ad1773512ed4f3df065d7","collectionId":"ea7ce336-dee5-4edf-81d5-ac1078d67c3a","schemaVersion":"v3","latestBuiltDeploymentHistoryId":"6a9ad1773512ed4f3df065d7"},"entitlements":{"AI_CHAT":{"status":"ENABLED"},"WEB_MCP":{"status":"ENABLED"},"NARRATION":{"status":"ENABLED"}},"buildId":"6a9ad1773512ed4f3df065d7","clientVersion":"0.0.4044","searchFilterCounts":[{"language":"default","tag":"API Reference","count":424},{"language":"default","tag":"Guides","count":200},{"language":"default","tag":"Examples","count":112},{"language":"default","tag":"Array Manipulation","count":48},{"language":"default","tag":"Math","count":48},{"language":"default","tag":"Reductions \u0026 Statistics","count":40},{"language":"default","tag":"Array Creation","count":32},{"language":"default","tag":"Linear Algebra","count":32},{"language":"default","tag":"Logic \u0026 Comparison","count":32},{"language":"default","tag":"Random (np.random)","count":32}]},"assistantConfig":{"enableAskAiButton":false,"enableStarterQuestions":false,"enableAskAiSearchBar":true},"basePath":"","hasChatPermissions":true,"hasWebMcpPermissions":true,"toggles":[{"name":"kill-isr","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"agent-mintlify-slack","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"agent-integrations-settings","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"automations-pr-grouping","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"custom-prefix","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"analytics-v7","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"user-flows-analytics","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"no-publish-flow","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-onboarding","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"llms-txt-v2","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"snapshot-serving-live","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"stripTemperatureMiddleware","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"support-platform-pylon-zendesk","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"snapshot-serving","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"instant-rollback","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"granular-notifications-server","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"granular-notifications","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"automations-fable","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"fixed-ai-action-pricing","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"automation-resolve-merge-conflict","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"scoped-publishing","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"mintql","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"page-level-analytics","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"editor-version-history-v2","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"billing-page-v2","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"full-page-search","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workspace-projects","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"assistant-v5","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"byok-sep-25","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"fork-pr-previews","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"revalidation-jwt","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"vite-origin","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"billing-updated-9-15","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-sso-scim","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"hobby-abuse-scan","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"dashboard-inbox","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-signup","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"turbopuffer-dual-write","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-enabled","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"approve-review-flow","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"sso-setup-deadline-banner","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false}],"googleFontsInlined":false},"customCss":[{"filePath":"style.css","content":"div[class*=mt-8][class*=\"lg:mt-0\"][class*=flex][class*=\"xl:hidden\"]{display:none!important}.chat-assistant-floating-input{visibility:hidden!important;pointer-events:none!important}"}],"page":{"pagePath":"v1.1.x/examples/performance-tips","slug":"/v1.1.x/examples/performance-tips","pageMetadata":{"title":"Performance Tips","description":"Optimize numpy-ts usage: avoid unnecessary copies, leverage views, tree-shake bundles, choose efficient dtypes, and prefer vectorized operations.","canonical":"https://numpyts.dev/latest/examples/performance-tips","href":"/v1.1.x/examples/performance-tips"},"description":{"compiledSource":"\"use strict\";\nconst {jsx: _jsx} = arguments[0];\nconst {useMDXComponents: _provideComponents} = arguments[0];\nfunction _createMdxContent(props) {\n const _components = {\n p: \"p\",\n ..._provideComponents(),\n ...props.components\n };\n return _jsx(_components.p, {\n children: \"Optimize numpy-ts usage: avoid unnecessary copies, leverage views, tree-shake bundles, choose efficient dtypes, and prefer vectorized operations.\"\n });\n}\nfunction MDXContent(props = {}) {\n const {wrapper: MDXLayout} = {\n ..._provideComponents(),\n ...props.components\n };\n return MDXLayout ? _jsx(MDXLayout, {\n ...props,\n children: _jsx(_createMdxContent, {\n ...props\n })\n }) : _createMdxContent(props);\n}\nreturn {\n default: MDXContent\n};\n","frontmatter":{},"scope":{}},"pageType":"default","mdx":{"mdxSource":{"compiledSource":"\"use strict\";const{Fragment:_Fragment,jsx:_jsx,jsxs:_jsxs}=arguments[0];const{useMDXComponents:_provideComponents}=arguments[0];const Playground=({code:singleCode=``,label=``,height=null,startingHeight=null,showImportHeader=false,showCopyButton=false,showTiming=true})=>{const NUMPY_TS_CDN_VERSION=`1.3.0`;const CDN_URLS={numpyTs:`https://cdn.jsdelivr.net/npm/numpy-ts@${NUMPY_TS_CDN_VERSION}/dist/numpy-ts.browser.js`,prismCore:`https://cdn.jsdelivr.net/npm/prismjs@1/prism.min.js`,prismTS:`https://cdn.jsdelivr.net/npm/prismjs@1/components/prism-typescript.min.js`,prismCSSLight:`https://cdn.jsdelivr.net/npm/prismjs@1/themes/prism.min.css`,prismCSSDark:`https://cdn.jsdelivr.net/npm/prismjs@1/themes/prism-tomorrow.min.css`};const SHARED_FONT={fontFamily:`'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace`,fontSize:`13px`,lineHeight:`1.5`,tabSize:2};const THEME_COLORS={light:{editorBg:`#f5f5f5`,editorText:`#24292e`,editorBorder:`#d1d5da`,toolbarBg:`#ffffff`,outputBg:`#fafbfc`,outputText:`#24292e`,selectBg:`#ffffff`,selectText:`#24292e`,selectBorder:`#d1d5da`,caretColor:`#000000`,placeholderText:`#6a737d`,resizeHandleBg:`#d1d5da`,resizeHandleHoverBg:`#959da5`},dark:{editorBg:`#1e1e1e`,editorText:`#d4d4d4`,editorBorder:`#333333`,toolbarBg:`#161616`,outputBg:`#1a1a1a`,outputText:`#d4d4d4`,selectBg:`#2a2a2a`,selectText:`#cccccc`,selectBorder:`#444444`,caretColor:`#ffffff`,placeholderText:`#666666`,resizeHandleBg:`#333333`,resizeHandleHoverBg:`#555555`}};const BASE_MIN_HEIGHT=100;const MAX_HEIGHT=800;const IMPORT_HEADER_TEXT=`import * as np from 'numpy-ts';\\n\\n`;const parseHeightPx=value=>{if(value==null)return null;if(typeof value===`number`\u0026\u0026Number.isFinite(value))return value;if(typeof value===`string`){const parsed=parseFloat(value);if(Number.isFinite(parsed))return parsed}return null};const minHeightPx=BASE_MIN_HEIGHT;const clampHeight=h=>Math.max(minHeightPx,Math.min(MAX_HEIGHT,h));const estimateSingleCodeHeight=(script,includeImportHeader)=>{const normalized=(script||``).replace(/\\r\\n/g,`\n`);const lineCount=normalized.length>0?normalized.split(`\n`).length:1;const fontSizePx=parseFloat(SHARED_FONT.fontSize)||13;const lineHeightRaw=parseFloat(SHARED_FONT.lineHeight);const lineHeightPx=(Number.isFinite(lineHeightRaw)?lineHeightRaw:1.5)*fontSizePx;const topPadding=includeImportHeader?16+3*fontSizePx:16;const bottomPadding=16;return Math.ceil(topPadding+bottomPadding+lineCount*lineHeightPx+4)};function loadScript(src){return new Promise((resolve,reject)=>{const existing=document.querySelector(`script[src=\"${src}\"]`);if(existing){if(existing.dataset.loaded===`true`){resolve();return}existing.addEventListener(`load`,resolve,{once:true});existing.addEventListener(`error`,reject,{once:true});return}const s=document.createElement(`script`);s.src=src;s.onload=()=>{s.dataset.loaded=`true`;resolve()};s.onerror=reject;document.head.appendChild(s)})}function loadCSS(href,removeOldId=null){if(document.querySelector(`link[href=\"${href}\"]`))return;if(removeOldId){const old=document.querySelector(`link[data-prism-theme=\"${removeOldId}\"]`);if(old)old.remove()}const l=document.createElement(`link`);l.rel=`stylesheet`;l.href=href;if(removeOldId)l.setAttribute(`data-prism-theme`,removeOldId);document.head.appendChild(l)}const startHeightPx=parseHeightPx(startingHeight)??parseHeightPx(height);const initialEditorHeight=startHeightPx!=null?clampHeight(startHeightPx):clampHeight(estimateSingleCodeHeight(singleCode,showImportHeader));const[code,setCode]=useState(singleCode);const[output,setOutput]=useState(``);const[loaded,setLoaded]=useState(false);const[loadError,setLoadError]=useState(null);const[running,setRunning]=useState(false);const[isDarkMode,setIsDarkMode]=useState(()=>document.documentElement.classList.contains(`dark`));const[editorHeight,setEditorHeight]=useState(initialEditorHeight);const[isResizing,setIsResizing]=useState(false);const[copied,setCopied]=useState(false);const[timing,setTiming]=useState(null);const[copyHover,setCopyHover]=useState(false);const[scrollbarWidth,setScrollbarWidth]=useState(0);const[toolbarNarrow,setToolbarNarrow]=useState(false);const textareaRef=useRef(null);const preRef=useRef(null);const codeRef=useRef(null);const toolbarRef=useRef(null);const resizeStartY=useRef(null);const resizeStartHeight=useRef(null);const runSeqRef=useRef(0);const npRef=useRef(null);const colors=THEME_COLORS[isDarkMode?`dark`:`light`];const copyTimeoutRef=useRef(null);useEffect(()=>{let cancelled=false;async function load(){try{loadCSS(isDarkMode?CDN_URLS.prismCSSDark:CDN_URLS.prismCSSLight,`prism`);const dynamicImport=new Function(`url`,`return import(url)`);const npModule=await dynamicImport(CDN_URLS.numpyTs);npRef.current=npModule.default??npModule;await loadScript(CDN_URLS.prismCore);await loadScript(CDN_URLS.prismTS);if(!cancelled){console.info(`[Playground] Loaded numpy-ts v${NUMPY_TS_CDN_VERSION} from CDN.`);setLoaded(true)}}catch(e){if(!cancelled)setLoadError(`Failed to load dependencies. Check your connection.`)}}load();return()=>{cancelled=true}},[]);const syncScroll=useCallback(()=>{if(!textareaRef.current||!codeRef.current)return;const ta=textareaRef.current;codeRef.current.style.transform=`translate(${-ta.scrollLeft}px, ${-ta.scrollTop}px)`},[]);useEffect(()=>{const observer=new MutationObserver(()=>{const isDark=document.documentElement.classList.contains(`dark`);setIsDarkMode(isDark);loadCSS(isDark?CDN_URLS.prismCSSDark:CDN_URLS.prismCSSLight,`prism`);if(loaded\u0026\u0026window.Prism){setTimeout(()=>{window.Prism.highlightAll();requestAnimationFrame(syncScroll)},50)}});observer.observe(document.documentElement,{attributes:true,attributeFilter:[`class`]});return()=>observer.disconnect()},[loaded,syncScroll]);useEffect(()=>{if(loaded\u0026\u0026window.Prism){window.Prism.highlightAll();requestAnimationFrame(syncScroll)}},[code,loaded,syncScroll]);const handleScroll=useCallback(()=>{syncScroll()},[syncScroll]);const handleKeyDown=useCallback(e=>{const ta=e.target;const start=ta.selectionStart;const end=ta.selectionEnd;const hasSelection=start!==end;if(e.key===`Tab`){e.preventDefault();const newVal=ta.value.substring(0,start)+` `+ta.value.substring(end);setCode(newVal);requestAnimationFrame(()=>{ta.selectionStart=ta.selectionEnd=start+2});return}if(e.key===`Enter`){e.preventDefault();const lineStart=ta.value.lastIndexOf(`\n`,start-1)+1;const lineTextUpToCursor=ta.value.substring(lineStart,start);const indent=(lineTextUpToCursor.match(/^[ \\t]*/)||[``])[0];const insert=`\\n${indent}`;const newVal=ta.value.substring(0,start)+insert+ta.value.substring(end);const nextPos=start+insert.length;setCode(newVal);requestAnimationFrame(()=>{ta.selectionStart=ta.selectionEnd=nextPos});return}if((e.metaKey||e.ctrlKey)\u0026\u0026!e.shiftKey\u0026\u0026!e.altKey\u0026\u0026e.key.toLowerCase()===`a`){e.preventDefault();ta.focus();ta.selectionStart=0;ta.selectionEnd=ta.value.length;return}if((e.metaKey||e.ctrlKey)\u0026\u0026!e.shiftKey\u0026\u0026!e.altKey\u0026\u0026e.key.toLowerCase()===`c`){e.preventDefault();const prevStart=ta.selectionStart;const prevEnd=ta.selectionEnd;let copyStart=prevStart;let copyEnd=prevEnd;if(!hasSelection){const lineStart=ta.value.lastIndexOf(`\n`,start-1)+1;const lineEndRaw=ta.value.indexOf(`\n`,start);const lineEnd=lineEndRaw===-1?ta.value.length:lineEndRaw;copyStart=lineStart;copyEnd=lineEnd}ta.focus();ta.selectionStart=copyStart;ta.selectionEnd=copyEnd;let copied=false;try{copied=typeof document.execCommand===`function`?document.execCommand(`copy`):false}catch{copied=false}if(!copied\u0026\u0026navigator.clipboard?.writeText){void navigator.clipboard.writeText(ta.value.substring(copyStart,copyEnd)).catch(()=>{})}requestAnimationFrame(()=>{ta.selectionStart=prevStart;ta.selectionEnd=prevEnd});return}if((e.metaKey||e.ctrlKey)\u0026\u0026!e.shiftKey\u0026\u0026!e.altKey\u0026\u0026(e.key===`/`||e.code===`Slash`)){e.preventDefault();const lineStart=ta.value.lastIndexOf(`\n`,start-1)+1;const endForLineCalc=hasSelection\u0026\u0026ta.value[end-1]===`\n`?end-1:end;const lineEndRaw=ta.value.indexOf(`\n`,endForLineCalc);const lineEnd=lineEndRaw===-1?ta.value.length:lineEndRaw;const block=ta.value.substring(lineStart,lineEnd);const lines=block.split(`\n`);const isCommentedLine=line=>/^(\\s*)\\/\\//.test(line);const nonEmptyLines=lines.filter(line=>line.trim().length>0);const shouldUncomment=nonEmptyLines.length>0\u0026\u0026nonEmptyLines.every(isCommentedLine);const toggleLine=line=>{if(line.trim().length===0)return line;if(shouldUncomment)return line.replace(/^(\\s*)\\/\\/ ?/,`$1`);const match=line.match(/^(\\s*)/);const indent=match?match[1]:``;return`${indent}// ${line.slice(indent.length)}`};const updatedLines=lines.map(toggleLine);const replacedBlock=updatedLines.join(`\n`);const newVal=ta.value.substring(0,lineStart)+replacedBlock+ta.value.substring(lineEnd);setCode(newVal);requestAnimationFrame(()=>{if(hasSelection){ta.selectionStart=lineStart;ta.selectionEnd=lineStart+replacedBlock.length;return}const line=lines[0]||``;const cursorCol=start-lineStart;let newCursorCol=cursorCol;if(line.trim().length>0){if(shouldUncomment){const uncommentMatch=line.match(/^(\\s*)\\/\\/ ?/);if(uncommentMatch){const indentLen=uncommentMatch[1].length;const removedLen=uncommentMatch[0].length-indentLen;if(cursorCol>indentLen){newCursorCol=Math.max(indentLen,cursorCol-removedLen)}}}else{const indentLen=(line.match(/^(\\s*)/)||[``])[0].length;if(cursorCol>indentLen){newCursorCol=cursorCol+3}}}const newCursor=lineStart+newCursorCol;ta.selectionStart=ta.selectionEnd=newCursor})}},[]);const handleResizeStart=useCallback(e=>{e.preventDefault();setIsResizing(true);resizeStartY.current=e.clientY;resizeStartHeight.current=editorHeight},[editorHeight]);useEffect(()=>{if(!isResizing)return;const handleMouseMove=e=>{const delta=e.clientY-resizeStartY.current;const newHeight=Math.max(minHeightPx,Math.min(MAX_HEIGHT,resizeStartHeight.current+delta));setEditorHeight(newHeight)};const handleMouseUp=()=>{setIsResizing(false)};window.addEventListener(`mousemove`,handleMouseMove);window.addEventListener(`mouseup`,handleMouseUp);return()=>{window.removeEventListener(`mousemove`,handleMouseMove);window.removeEventListener(`mouseup`,handleMouseUp)}},[isResizing,minHeightPx]);useEffect(()=>{if(startHeightPx!=null){setEditorHeight(clampHeight(startHeightPx))}else{setEditorHeight(clampHeight(estimateSingleCodeHeight(singleCode,showImportHeader)))}},[startHeightPx,singleCode,showImportHeader]);const run=useCallback(async()=>{if(!loaded||!npRef.current)return;const runId=runSeqRef.current+1;runSeqRef.current=runId;setRunning(true);setTiming(null);const logs=[];const origLog=console.log;const origError=console.error;const origWarn=console.warn;const fmt=(...args)=>args.map(a=>{if(a==null)return String(a);if(typeof a===`object`\u0026\u0026typeof a.toString===`function`\u0026\u0026a.toString!==Object.prototype.toString)return a.toString();if(typeof a===`object`){try{return JSON.stringify(a)}catch{return String(a)}}return String(a)}).join(` `);console.log=(...args)=>logs.push(fmt(...args));console.error=(...args)=>logs.push(`Error: `+fmt(...args));console.warn=(...args)=>logs.push(`Warning: `+fmt(...args));let hasError=false;const shouldRunAsync=/\\bawait\\b/.test(code);const t0=performance.now();try{let result;if(shouldRunAsync){const executeAsync=new Function(`np`,`\"use strict\"; return (async () => {\\n${code}\\n})();`);result=await executeAsync(npRef.current)}else{const executeSync=new Function(`np`,code);result=executeSync(npRef.current)}if(result!==undefined){logs.push(typeof result===`object`\u0026\u0026typeof result?.toString===`function`\u0026\u0026result.toString!==Object.prototype.toString?result.toString():String(result))}}catch(e){hasError=true;logs.push(`Error: `+(e?.message||String(e)))}finally{console.log=origLog;console.error=origError;console.warn=origWarn}const elapsed=performance.now()-t0;if(runId!==runSeqRef.current)return;setOutput(logs.join(`\n`));if(showTiming\u0026\u0026!hasError){const formatted=elapsed\u003c.15?`\u003c 0.10 ms`:elapsed\u003c1?elapsed.toFixed(2)+` ms`:elapsed\u003c1e3?elapsed.toFixed(1)+` ms`:(elapsed/1e3).toFixed(2)+` s`;setTiming(formatted)}setRunning(false)},[loaded,code,showTiming]);const handleCopy=useCallback(async()=>{const textToCopy=`${showImportHeader?IMPORT_HEADER_TEXT:``}${code}`;try{await navigator.clipboard.writeText(textToCopy);setCopied(true);if(copyTimeoutRef.current)clearTimeout(copyTimeoutRef.current);copyTimeoutRef.current=setTimeout(()=>setCopied(false),1200)}catch{setCopied(false)}},[code,showImportHeader]);useEffect(()=>{return()=>{if(copyTimeoutRef.current)clearTimeout(copyTimeoutRef.current)}},[]);useEffect(()=>{const measureScrollbar=()=>{if(!textareaRef.current)return;const el=textareaRef.current;const width=Math.max(el.offsetWidth-el.clientWidth,0);setScrollbarWidth(width)};measureScrollbar();window.addEventListener(`resize`,measureScrollbar);return()=>window.removeEventListener(`resize`,measureScrollbar)},[editorHeight,code,showImportHeader]);useEffect(()=>{if(!toolbarRef.current)return;const ro=new ResizeObserver(([entry])=>{setToolbarNarrow(entry.contentRect.width\u003c380)});ro.observe(toolbarRef.current);return()=>ro.disconnect()},[]);if(loadError){return _jsx(`div`,{style:{padding:`20px`,color:`#e55`,background:colors.outputBg,borderRadius:`8px`,fontSize:`14px`},children:loadError})}const editorRadius=`8px 8px 0 0`;const editorContentRadius=`8px 8px 0 0`;const editorWrap={position:`relative`,height:`${editorHeight}px`,overflow:`hidden`};const editorBorderOverlay={position:`absolute`,inset:0,borderRadius:editorRadius,border:`1px solid ${colors.editorBorder}`,borderBottom:`none`,pointerEvents:`none`,zIndex:4};const copyWrapStyle={position:`absolute`,top:`8px`,right:`${10+scrollbarWidth}px`,zIndex:3,display:`inline-flex`,alignItems:`center`,gap:`6px`};const copyTooltipVisible=copied||copyHover;const copyTooltipStyle={fontSize:`11px`,lineHeight:1,color:`#ffffff`,background:`#3b82f6`,border:`1px solid #3b82f6`,borderRadius:`6px`,padding:`4px 8px`,opacity:copyTooltipVisible?1:0,transform:copyTooltipVisible?`translateY(0)`:`translateY(2px)`,transition:`opacity 0.15s, transform 0.15s`,pointerEvents:`none`,whiteSpace:`nowrap`};const copyBtnStyle={width:`24px`,height:`24px`,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`6px`,border:`none`,background:`transparent`,color:isDarkMode?`rgba(255,255,255,0.4)`:`#9ca3af`,cursor:`pointer`,padding:0,lineHeight:1};const sharedTextStyle={margin:0,border:0,padding:`16px`,whiteSpace:`pre`,overflowWrap:`normal`,wordBreak:`normal`,verticalAlign:`baseline`,textRendering:`auto`};const preStyle={...SHARED_FONT,...sharedTextStyle,position:`absolute`,top:0,left:0,right:0,bottom:0,background:colors.editorBg,overflow:`hidden`,pointerEvents:`none`,padding:0,borderRadius:editorContentRadius};const codeStyle={display:`block`,...SHARED_FONT,background:`transparent`,padding:`16px`,margin:0,border:0,whiteSpace:`pre`,overflowWrap:`normal`,wordBreak:`normal`,lineHeight:`inherit`,willChange:`transform`};const textareaStyle={...SHARED_FONT,...sharedTextStyle,position:`absolute`,top:0,left:0,right:0,bottom:0,paddingTop:showImportHeader?`calc(16px + 3em)`:`16px`,background:`transparent`,color:`transparent`,caretColor:colors.caretColor,outline:`none`,resize:`none`,overflow:`auto`,WebkitTextFillColor:`transparent`,zIndex:1,width:`100%`,height:`100%`,borderRadius:editorContentRadius};const resizeHandle={height:`4px`,background:isResizing?colors.resizeHandleHoverBg:colors.resizeHandleBg,cursor:`ns-resize`,transition:`background 0.15s`,borderLeft:`1px solid ${colors.editorBorder}`,borderRight:`1px solid ${colors.editorBorder}`};const toolbarStyle={display:`flex`,alignItems:`center`,gap:`8px`,padding:`8px 12px`,background:colors.toolbarBg,borderLeft:`1px solid ${colors.editorBorder}`,borderRight:`1px solid ${colors.editorBorder}`,flexWrap:`wrap`};const btnStyle={display:`inline-flex`,alignItems:`center`,gap:`6px`,padding:`6px 16px`,background:`#3179C7`,color:`#fff`,border:`none`,borderRadius:`6px`,fontSize:`13px`,fontWeight:500,cursor:loaded?`pointer`:`not-allowed`,opacity:loaded?1:.5,transition:`background 0.15s`};const selectStyle={padding:`6px 10px`,background:colors.selectBg,color:colors.selectText,border:`1px solid ${colors.selectBorder}`,borderRadius:`6px`,fontSize:`13px`,cursor:`pointer`,outline:`none`};const badgeStyle={marginLeft:`auto`,fontSize:`11px`,color:colors.placeholderText,display:`flex`,alignItems:`center`,gap:`4px`,whiteSpace:`nowrap`};const outputStyle={margin:0,padding:`16px`,minHeight:`60px`,maxHeight:`240px`,overflow:`auto`,...SHARED_FONT,fontSize:`12.5px`,background:colors.outputBg,color:colors.outputText,borderRadius:`0 0 8px 8px`,border:`1px solid ${colors.editorBorder}`,borderTop:`none`,whiteSpace:`pre-wrap`,overflowWrap:`break-word`};const renderedCode=`${showImportHeader?IMPORT_HEADER_TEXT:``}${code}`;const runSpinnerStyle={animation:`playgroundSpin 0.9s linear infinite`,display:`inline-block`};return _jsxs(`div`,{children:[_jsx(`style`,{children:`\n @keyframes playgroundSpin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n @keyframes playgroundPulse {\n 0%, 100% { opacity: 0.45; transform: scale(1); }\n 50% { opacity: 1; transform: scale(1.12); }\n }\n code[class*=\"language-\"] {\n white-space: pre !important;\n word-break: normal !important;\n overflow-wrap: normal !important;\n }\n `}),label?_jsx(`div`,{style:{marginTop:`8px`,marginBottom:`8px`,fontSize:`14px`,fontWeight:500,color:colors.editorText},children:label}):null,_jsxs(`div`,{style:editorWrap,children:[_jsx(`div`,{style:editorBorderOverlay,\"aria-hidden\":`true`}),showCopyButton?_jsxs(`div`,{style:copyWrapStyle,children:[_jsx(`span`,{style:copyTooltipStyle,children:copied?`Copied`:`Copy`}),_jsx(`button`,{type:`button`,onClick:handleCopy,style:copyBtnStyle,onMouseEnter:e=>{setCopyHover(true);e.currentTarget.style.color=isDarkMode?`rgba(255,255,255,0.6)`:`#6b7280`},onMouseLeave:e=>{setCopyHover(false);e.currentTarget.style.color=isDarkMode?`rgba(255,255,255,0.4)`:`#9ca3af`},\"aria-label\":`Copy code`,children:copied?_jsx(`svg`,{width:`18`,height:`18`,viewBox:`0 0 20 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,\"aria-hidden\":`true`,children:_jsx(`path`,{d:`M4.5 10.5L8.2 14.2L15.5 6.8`,stroke:`#3b82f6`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})}):_jsxs(`svg`,{width:`18`,height:`18`,viewBox:`0 0 18 18`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,\"aria-hidden\":`true`,children:[_jsx(`path`,{d:`M14.25 5.25H7.25C6.14543 5.25 5.25 6.14543 5.25 7.25V14.25C5.25 15.3546 6.14543 16.25 7.25 16.25H14.25C15.3546 16.25 16.25 15.3546 16.25 14.25V7.25C16.25 6.14543 15.3546 5.25 14.25 5.25Z`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),_jsx(`path`,{d:`M2.80103 11.998L1.77203 5.07397C1.61003 3.98097 2.36403 2.96397 3.45603 2.80197L10.38 1.77297C11.313 1.63397 12.19 2.16297 12.528 3.00097`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]}):null,_jsx(`pre`,{ref:preRef,style:preStyle,children:_jsx(`code`,{ref:codeRef,className:`language-typescript`,style:codeStyle,children:renderedCode})}),_jsx(`textarea`,{ref:textareaRef,value:code,onChange:e=>setCode(e.target.value),onScroll:handleScroll,onKeyDown:handleKeyDown,style:textareaStyle,spellCheck:false,wrap:`off`,autoCapitalize:`off`,autoCorrect:`off`,\"aria-label\":`Code editor`})]}),_jsx(`div`,{style:resizeHandle,onMouseDown:handleResizeStart,onMouseEnter:e=>!isResizing\u0026\u0026(e.target.style.background=colors.resizeHandleHoverBg),onMouseLeave:e=>!isResizing\u0026\u0026(e.target.style.background=colors.resizeHandleBg),\"aria-label\":`Resize editor`,role:`separator`}),_jsxs(`div`,{ref:toolbarRef,style:toolbarStyle,children:[_jsx(`button`,{onClick:run,disabled:!loaded,style:btnStyle,onMouseEnter:e=>loaded\u0026\u0026(e.target.style.background=`#2668b0`),onMouseLeave:e=>loaded\u0026\u0026(e.target.style.background=`#3179C7`),children:running?_jsxs(_Fragment,{children:[_jsx(`span`,{style:runSpinnerStyle,children:`↻`}),` Run`]}):_jsxs(_Fragment,{children:[_jsx(`span`,{children:`▶`}),` Run`]})}),timing\u0026\u0026!running\u0026\u0026_jsx(`span`,{style:{fontSize:`12px`,color:`#4caf50`,fontWeight:500,whiteSpace:`nowrap`},children:toolbarNarrow?timing:`Completed in ${timing}`}),_jsx(`span`,{style:badgeStyle,children:loaded?_jsxs(_Fragment,{children:[_jsx(`span`,{style:{color:`#4caf50`,display:`inline-block`,animation:`playgroundPulse 2.2s ease-in-out infinite`,transformOrigin:`center`},children:`●`}),` Runs in your browser`]}):_jsxs(_Fragment,{children:[_jsx(`span`,{style:{animation:`spin 1s linear infinite`,display:`inline-block`},children:`↻`}),` Loading numpy-ts...`]})})]}),_jsx(`pre`,{style:outputStyle,children:output||_jsx(`span`,{style:{color:colors.placeholderText,fontStyle:`italic`},children:`Click Run to execute the code above`})})]})};function _createMdxContent(props){const _components={code:`code`,hr:`hr`,p:`p`,tbody:`tbody`,td:`td`,th:`th`,thead:`thead`,tr:`tr`,..._provideComponents(),...props.components},{Heading,Table,Tip,Warning,_MdxComponentBoundary}=_components;if(!Heading)_missingMdxReference(`Heading`,true);if(!Table)_missingMdxReference(`Table`,true);if(!Tip)_missingMdxReference(`Tip`,true);if(!Warning)_missingMdxReference(`Warning`,true);if(!_MdxComponentBoundary)_missingMdxReference(`_MdxComponentBoundary`,true);return _jsxs(_Fragment,{children:[_jsx(Heading,{level:`2`,id:`vectorized-operations-vs-loops`,children:`Vectorized operations vs loops`}),`\n`,_jsx(_components.p,{children:`Always prefer vectorized operations over JavaScript loops. numpy-ts operations run on typed arrays with optimized internal loops, avoiding the overhead of JavaScript function calls and dynamic type checks.`}),`\n`,_jsx(_MdxComponentBoundary,{name:`Playground`,children:_jsx(Playground,{code:[`const n = 1000000;`,`const a = np.random.random([n]);`,`const b = np.random.random([n]);`,``,`// BAD: JavaScript loop (slow)`,`const t0 = performance.now();`,`const resultLoop = np.zeros([n]);`,`const aArr = a.toArray();`,`const bArr = b.toArray();`,`for (let i = 0; i \u003c n; i++) {`,` // Each iteration has JS overhead`,` resultLoop.set([i], Math.sqrt(aArr[i] * aArr[i] + bArr[i] * bArr[i]));`,`}`,`const t1 = performance.now();`,`console.log('Loop time (ms):', (t1 - t0).toFixed(2), '\\\\n');`,``,`// GOOD: Vectorized (fast)`,`const t2 = performance.now();`,`const resultVec = np.power(a, 2).add(np.power(b, 2)).sqrt();`,`const t3 = performance.now();`,`console.log('Vectorized time (ms):', (t3 - t2).toFixed(2), '\\\\n');`,`console.log('Speedup:', ((t1 - t0) / (t3 - t2)).toFixed(2) + 'x');`,``,`// Sanity check: compare arrays (max absolute difference)`,`const diff = np.abs(np.subtract(resultLoop, resultVec));`,`const maxDiff = np.amax(diff);`,`console.log('Results match:', maxDiff \u003c 0.001 ? true : false);`].join(`\n`),showImportHeader:true,showCopyButton:true})}),`\n`,_jsx(Heading,{level:`3`,id:`common-loop-to-vectorized-translations`,children:`Common loop-to-vectorized translations`}),`\n`,_jsxs(Table,{children:[_jsx(_components.thead,{children:_jsxs(_components.tr,{children:[_jsx(_components.th,{children:`Loop pattern`}),_jsx(_components.th,{children:`Vectorized equivalent`})]})}),_jsxs(_components.tbody,{children:[_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`for (i) result[i] = a[i] + b[i]`})}),_jsx(_components.td,{children:_jsx(_components.code,{children:`np.add(a, b)`})})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`for (i) result[i] = a[i] > threshold ? 1 : 0`})}),_jsx(_components.td,{children:_jsx(_components.code,{children:`np.greater(a, threshold)`})})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`for (i) sum += a[i]`})}),_jsx(_components.td,{children:_jsx(_components.code,{children:`np.sum(a)`})})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`for (i) result[i] = Math.max(a[i], 0)`})}),_jsx(_components.td,{children:_jsx(_components.code,{children:`np.maximum(a, 0)`})})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`for (i) if (mask[i]) result.push(a[i])`})}),_jsx(_components.td,{children:_jsx(_components.code,{children:`np.extract(mask, a)`})})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`for (i) result[i] = condition ? x[i] : y[i]`})}),_jsx(_components.td,{children:_jsx(_components.code,{children:`np.where(condition, x, y)`})})]})]})]}),`\n`,_jsx(_components.hr,{}),`\n`,_jsx(Heading,{level:`2`,id:`avoiding-unnecessary-copies-use-views-when-possible`,children:`Avoiding unnecessary copies (use views when possible)`}),`\n`,_jsx(_components.p,{children:`Views share the same underlying data buffer as the original array. Operations that return views are effectively free — no memory allocation and no data copying.`}),`\n`,_jsx(_MdxComponentBoundary,{name:`Playground`,children:_jsx(Playground,{code:String.raw`const data = np.arange(1000000); // 1 million elements\n\n// These return views (fast, no copy):\nconst reshaped = np.reshape(data, [1000, 1000]); // view\nconst transposed = reshaped.T; // view\nconst sliced = reshaped.slice('0:500', ':'); // view\nconst squeezed = np.expand_dims(data, 0); // view\n\n// These always copy (allocate new memory):\nconst flattened = np.flatten(transposed); // copy (transpose is not contiguous)\nconst copied = np.copy(data); // explicit copy\nconst tiled = np.tile(data, [2]); // copy`,showImportHeader:true,showCopyButton:true})}),`\n`,_jsx(Heading,{level:`3`,id:`check-whether-an-operation-returned-a-view`,children:`Check whether an operation returned a view`}),`\n`,_jsx(_MdxComponentBoundary,{name:`Playground`,children:_jsx(Playground,{code:String.raw`const a = np.arange(12).reshape([3, 4]);\nconst b = a.slice('0:2', ':');\n\nconsole.log(b.flags.OWNDATA, '\\n');\nconsole.log(b.base === a, '\\n');\n\nconst c = np.flatten(a);\nconsole.log(c.flags.OWNDATA, '\\n');`,showImportHeader:true,showCopyButton:true})}),`\n`,_jsx(Warning,{children:_jsxs(_components.p,{children:[`Views share data. Modifying a view changes the original array. If you need an independent copy, use `,_jsx(_components.code,{children:`np.copy()`}),` or `,_jsx(_components.code,{children:`.copy()`}),`.`]})}),`\n`,_jsx(_components.hr,{}),`\n`,_jsx(Heading,{level:`2`,id:`dtype-selection-for-memory-efficiency`,children:`Dtype selection for memory efficiency`}),`\n`,_jsx(_components.p,{children:`Choose the smallest dtype that can represent your data. This reduces memory usage and can improve cache performance.`}),`\n`,_jsx(_MdxComponentBoundary,{name:`Playground`,children:_jsx(Playground,{code:String.raw`// Default float64: 8 bytes per element\nconst f64 = np.zeros([1000, 1000]); // ~8 MB\nconsole.log(f64.tobytes().byteLength);\n\n// float32: 4 bytes per element, sufficient for most ML/graphics\nconst f32 = np.zeros([1000, 1000], 'float32'); // ~4 MB\nconsole.log(f32.tobytes().byteLength);\n\n// int8: 1 byte per element, good for small integer data\nconst i8 = np.zeros([1000, 1000], 'int8'); // ~1 MB\nconsole.log(i8.tobytes().byteLength);`,showImportHeader:true,showCopyButton:true})}),`\n`,_jsx(Heading,{level:`3`,id:`dtype-selection-guide`,children:`Dtype selection guide`}),`\n`,_jsxs(Table,{children:[_jsx(_components.thead,{children:_jsxs(_components.tr,{children:[_jsx(_components.th,{children:`Data type`}),_jsx(_components.th,{children:`Bytes`}),_jsx(_components.th,{children:`Use when`})]})}),_jsxs(_components.tbody,{children:[_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`float64`})}),_jsx(_components.td,{\"data-numeric\":`true`,children:`8`}),_jsx(_components.td,{children:`Maximum precision needed, scientific computation`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`float32`})}),_jsx(_components.td,{\"data-numeric\":`true`,children:`4`}),_jsx(_components.td,{children:`ML inference, graphics, when 7 digits of precision suffice`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`int32`})}),_jsx(_components.td,{\"data-numeric\":`true`,children:`4`}),_jsx(_components.td,{children:`Integer data up to ~2 billion`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`int16`})}),_jsx(_components.td,{\"data-numeric\":`true`,children:`2`}),_jsx(_components.td,{children:`Audio samples, small integer ranges`})]}),_jsxs(_components.tr,{children:[_jsxs(_components.td,{children:[_jsx(_components.code,{children:`int8`}),` / `,_jsx(_components.code,{children:`uint8`})]}),_jsx(_components.td,{\"data-numeric\":`true`,children:`1`}),_jsx(_components.td,{children:`Pixel values, boolean-like data, lookup indices`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.code,{children:`bool`})}),_jsx(_components.td,{\"data-numeric\":`true`,children:`1`}),_jsx(_components.td,{children:`Masks and boolean arrays`})]})]})]}),`\n`,_jsx(Tip,{children:_jsxs(_components.p,{children:[`Use `,_jsx(_components.code,{children:`.astype()`}),` to convert between dtypes. Going from a wider type to a narrower one truncates (float to int) or wraps (large int to small int).`]})}),`\n`,_jsx(_components.hr,{}),`\n`,_jsx(Heading,{level:`2`,id:`using-keepdims-for-broadcasting`,children:`Using keepdims for broadcasting`}),`\n`,_jsxs(_components.p,{children:[`When reducing along an axis, the reduced dimension disappears by default. Use `,_jsx(_components.code,{children:`keepdims: true`}),` to preserve it as a size-1 dimension, which makes subsequent broadcasting operations work without manual reshaping.`]}),`\n`,_jsx(_MdxComponentBoundary,{name:`Playground`,children:_jsx(Playground,{code:String.raw`const data = np.array([[1, 2, 3], [4, 5, 6]]); // shape [2, 3]\n\n// Without keepdims: shape [2] -- cannot directly broadcast with [2, 3]\nconst rowMeans = np.mean(data, 1);\nconsole.log(rowMeans.shape, '\\n');\n// np.subtract(data, rowMeans) -- would need reshape\n\n// With keepdims: shape [2, 1] -- broadcasts naturally with [2, 3]\nconst rowMeansKept = np.mean(data, 1, true);\nconsole.log(rowMeansKept.shape, '\\n');\n\n// Center the data (subtract row means) -- no reshape needed\nconst centered = np.subtract(data, rowMeansKept);\nconsole.log(centered, '\\n');\n\n// Normalize columns to zero mean, unit variance\nconst colMean = np.mean(data, 0, true); // shape [1, 3]\nconst colStd = np.std(data, 0, undefined, true); // shape [1, 3]\nconst normalized = np.divide(np.subtract(data, colMean), colStd);\nconsole.log(normalized, '\\n');`,showImportHeader:true,showCopyButton:true})})]})}function MDXContent(props={}){const{wrapper:MDXLayout}={..._provideComponents(),...props.components};return MDXLayout?_jsx(MDXLayout,{...props,children:_jsx(_createMdxContent,{...props})}):_createMdxContent(props)}return{Playground,default:MDXContent};function _missingMdxReference(id,component){throw new Error(`Expected `+(component?`component`:`object`)+\" `\"+id+\"` to be defined: you likely forgot to import, pass, or provide it.\")}","frontmatter":{},"scope":{"config":{},"pageMetadata":{"title":"Performance Tips","description":"Optimize numpy-ts usage: avoid unnecessary copies, leverage views, tree-shake bundles, choose efficient dtypes, and prefer vectorized operations.","canonical":"https://numpyts.dev/latest/examples/performance-tips","href":"/v1.1.x/examples/performance-tips"}}},"mdxSourceWithNoJs":null,"noJsSplices":[[146,20781,")=>null;function _cr"],[21725,22754,""],[24974,25552,""],[25806,26027,""],[26720,27185,""],[29839,30682,""]]},"mdxExtracts":{"tableOfContents":[{"title":"Vectorized operations vs loops","slug":"vectorized-operations-vs-loops","depth":2,"children":[{"title":"Common loop-to-vectorized translations","slug":"common-loop-to-vectorized-translations","depth":3,"children":[]}]},{"title":"Avoiding unnecessary copies (use views when possible)","slug":"avoiding-unnecessary-copies-use-views-when-possible","depth":2,"children":[{"title":"Check whether an operation returned a view","slug":"check-whether-an-operation-returned-a-view","depth":3,"children":[]}]},{"title":"Dtype selection for memory efficiency","slug":"dtype-selection-for-memory-efficiency","depth":2,"children":[{"title":"Dtype selection guide","slug":"dtype-selection-guide","depth":3,"children":[]}]},{"title":"Using keepdims for broadcasting","slug":"using-keepdims-for-broadcasting","depth":2,"children":[]}],"codeExamples":{}},"jsLinks":[],"subdomain":"none-4568e96a","siteName":"numpy-ts","title":"Performance Tips - numpy-ts","navMaps":{"firstHrefInVersion":{"v1.7.x":{"href":"/latest/examples/performance-tips","matchLevel":1},"v1.6.x":{"href":"/v1.6.x/examples/performance-tips","matchLevel":1,"canonicalOverride":true},"v1.5.x":{"href":"/v1.5.x/examples/performance-tips","matchLevel":1,"canonicalOverride":true},"v1.4.x":{"href":"/v1.4.x/examples/performance-tips","matchLevel":1,"canonicalOverride":true},"v1.3.x":{"href":"/v1.3.x/examples/performance-tips","matchLevel":1,"canonicalOverride":true},"v1.2.x":{"href":"/v1.2.x/examples/performance-tips","matchLevel":1,"canonicalOverride":true},"v1.1.x":{"href":"/v1.1.x/examples/performance-tips","matchLevel":0},"v1.0.x":{"href":"/v1.0.x/examples/performance-tips","matchLevel":1,"canonicalOverride":true}},"firstHrefInLanguage":{}},"lastModified":"2026-04-13T20:48:11.759Z","originalFileLocation":"v1.1.x/examples/performance-tips.mdx"},"headHtml":"\u003cscript data-mint-head>(function(){var d=document.documentElement,p=null;if(!p){try{p=localStorage.getItem(\"isDarkMode\")}catch(e){}if(p==='true')p='dark';else if(p==='false')p='light';if(p!=='light'\u0026\u0026p!=='dark'\u0026\u0026p!=='system')p=\"system\"}var r=p==='system'?(matchMedia(\"(prefers-color-scheme: dark)\").matches?'dark':'light'):p;d.classList.remove(r==='dark'?'light':'dark');d.classList.add(r);d.setAttribute(\"data-theme-preference\",p)})();\u003c/script>\u003cmeta data-mint-head name=\"description\" content=\"Optimize numpy-ts usage: avoid unnecessary copies, leverage views, tree-shake bundles, choose efficient dtypes, and prefer vectorized operations.\">\u003cmeta data-mint-head name=\"application-name\" content=\"numpy-ts\">\u003cmeta data-mint-head name=\"generator\" content=\"Mintlify\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"192x192\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/android-chrome-192x192.png\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"apple-touch-icon\" type=\"image/png\" sizes=\"180x180\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/apple-touch-icon.png\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/favicon-16x16.png\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/favicon-32x32.png\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/favicon.ico\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"192x192\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon-dark/android-chrome-192x192.png\" media=\"(prefers-color-scheme: dark)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon-dark/favicon-16x16.png\" media=\"(prefers-color-scheme: dark)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon-dark/favicon-32x32.png\" media=\"(prefers-color-scheme: dark)\">\u003clink data-mint-head rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon-dark/favicon.ico\" media=\"(prefers-color-scheme: dark)\">\u003cmeta data-mint-head property=\"og:title\" content=\"Performance Tips - numpy-ts\">\u003cmeta data-mint-head property=\"og:description\" content=\"Optimize numpy-ts usage: avoid unnecessary copies, leverage views, tree-shake bundles, choose efficient dtypes, and prefer vectorized operations.\">\u003cmeta data-mint-head property=\"og:site_name\" content=\"numpy-ts\">\u003cmeta data-mint-head property=\"og:url\" content=\"https://numpyts.dev/latest/examples/performance-tips\">\u003cmeta data-mint-head property=\"og:type\" content=\"website\">\u003cmeta data-mint-head property=\"og:image\" content=\"https://none-4568e96a.mintlify.app/_mintlify/api/og/v2?division=Examples\u0026amp;title=Performance+Tips\u0026amp;description=Optimize+numpy-ts+usage%3A+avoid+unnecessary+copies%2C+leverage+views%2C+tree-shake+bundles%2C+choose+efficient+dtypes%2C+and+prefer+vectorized+operations.\u0026amp;theme=e61fb829a0e28a90bc63de8c\u0026amp;signature=6db8948776d576eaf59588721d743e625f2ca8a01e4f3da03895c58b9f2c05c9\">\u003cmeta data-mint-head property=\"og:image:width\" content=\"1200\">\u003cmeta data-mint-head property=\"og:image:height\" content=\"630\">\u003cmeta data-mint-head name=\"twitter:card\" content=\"summary_large_image\">\u003cmeta data-mint-head name=\"twitter:title\" content=\"Performance Tips - numpy-ts\">\u003cmeta data-mint-head name=\"twitter:description\" content=\"Optimize numpy-ts usage: avoid unnecessary copies, leverage views, tree-shake bundles, choose efficient dtypes, and prefer vectorized operations.\">\u003cmeta data-mint-head name=\"twitter:image\" content=\"https://none-4568e96a.mintlify.app/_mintlify/api/og/v2?division=Examples\u0026amp;title=Performance+Tips\u0026amp;description=Optimize+numpy-ts+usage%3A+avoid+unnecessary+copies%2C+leverage+views%2C+tree-shake+bundles%2C+choose+efficient+dtypes%2C+and+prefer+vectorized+operations.\u0026amp;theme=e61fb829a0e28a90bc63de8c\u0026amp;signature=6db8948776d576eaf59588721d743e625f2ca8a01e4f3da03895c58b9f2c05c9\">\u003cmeta data-mint-head name=\"twitter:image:width\" content=\"1200\">\u003cmeta data-mint-head name=\"twitter:image:height\" content=\"630\">\u003cmeta data-mint-head name=\"msapplication-config\" content=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/browserconfig.xml\">\u003cmeta data-mint-head name=\"apple-mobile-web-app-title\" content=\"numpy-ts\">\u003cmeta data-mint-head name=\"msapplication-TileColor\" content=\"#3179C7\">\u003clink data-mint-head rel=\"canonical\" href=\"https://numpyts.dev/latest/examples/performance-tips\">\u003clink data-mint-head rel=\"alternate\" type=\"application/xml\" href=\"/sitemap.xml\">\u003clink data-mint-head rel=\"alternate\" type=\"text/markdown\" href=\"/v1.1.x/examples/performance-tips.md\">\u003cscript data-mint-head type=\"application/ld+json\">{\"@context\":\"https://schema.org\",\"@graph\":[{\"@type\":\"Organization\",\"@id\":\"https://numpyts.dev/#organization\",\"name\":\"numpy-ts\",\"url\":\"https://numpyts.dev\",\"logo\":{\"@type\":\"ImageObject\",\"url\":\"https://mintcdn.com/none-4568e96a/TklIwzPdQ8Sv_cxD/images/logo-light.svg?fit=max\u0026auto=format\u0026n=TklIwzPdQ8Sv_cxD\u0026q=85\u0026s=85a09d3e9971808ec73bf6e2eddcb989\"}},{\"@type\":\"WebSite\",\"@id\":\"https://numpyts.dev#website\",\"name\":\"numpy-ts\",\"url\":\"https://numpyts.dev\",\"publisher\":{\"@id\":\"https://numpyts.dev/#organization\"}},{\"@type\":\"WebPage\",\"@id\":\"https://numpyts.dev/latest/examples/performance-tips#webpage\",\"url\":\"https://numpyts.dev/latest/examples/performance-tips\",\"name\":\"Performance Tips\",\"description\":\"Optimize numpy-ts usage: avoid unnecessary copies, leverage views, tree-shake bundles, choose efficient dtypes, and prefer vectorized operations.\",\"dateModified\":\"2026-04-13T20:48:11.759Z\",\"isPartOf\":{\"@id\":\"https://numpyts.dev#website\"},\"breadcrumb\":{\"@id\":\"https://numpyts.dev/latest/examples/performance-tips#breadcrumb\"}},{\"@type\":\"BreadcrumbList\",\"@id\":\"https://numpyts.dev/latest/examples/performance-tips#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Examples\",\"item\":\"https://numpyts.dev/v1.1.x/examples/overview\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Performance Tips\",\"item\":\"https://numpyts.dev/latest/examples/performance-tips\"}]},{\"@type\":[\"Article\",\"TechArticle\"],\"@id\":\"https://numpyts.dev/latest/examples/performance-tips#article\",\"headline\":\"Performance Tips\",\"name\":\"Performance Tips\",\"description\":\"Optimize numpy-ts usage: avoid unnecessary copies, leverage views, tree-shake bundles, choose efficient dtypes, and prefer vectorized operations.\",\"url\":\"https://numpyts.dev/latest/examples/performance-tips\",\"mainEntityOfPage\":{\"@id\":\"https://numpyts.dev/latest/examples/performance-tips#webpage\"},\"dateModified\":\"2026-04-13T20:48:11.759Z\",\"publisher\":{\"@id\":\"https://numpyts.dev/#organization\"},\"isPartOf\":{\"@id\":\"https://numpyts.dev#website\"}}]}\u003c/script>\u003cscript data-mint-head type=\"application/ld+json\">{\"@context\":\"https://schema.org\",\"@type\":\"WebSite\",\"name\":\"numpy-ts\",\"creator\":{\"@type\":\"Organization\",\"name\":\"Mintlify\",\"url\":\"https://mintlify.com\"}}\u003c/script>","siteName":"numpy-ts","nav":{"global":null,"versions":[{"version":"v1.7.x","tag":"Latest","pages":[{"title":"v1.7.x","href":"/latest/examples/performance-tips"}]},{"version":"v1.6.x","pages":[{"title":"v1.6.x","href":"/v1.6.x/examples/performance-tips"}]},{"version":"v1.5.x","pages":[{"title":"v1.5.x","href":"/v1.5.x/examples/performance-tips"}]},{"version":"v1.4.x","pages":[{"title":"v1.4.x","href":"/v1.4.x/examples/performance-tips"}]},{"version":"v1.3.x","pages":[{"title":"v1.3.x","href":"/v1.3.x/examples/performance-tips"}]},{"version":"v1.2.x","pages":[{"title":"v1.2.x","href":"/v1.2.x/examples/performance-tips"}]},{"version":"v1.1.x","tabs":[{"tab":"Guides","pages":[{"title":"Guides","href":""}]},{"tab":"API Reference","pages":[{"title":"API Reference","href":"/v1.1.x/api/overview"}]},{"tab":"Examples","groups":[{"group":"Examples","pages":[{"title":"Examples","sidebarTitle":"Overview","href":"/v1.1.x/examples/overview"},{"title":"Linear Algebra","href":"/v1.1.x/examples/linear-algebra"},{"title":"Signal Processing with FFT","href":"/v1.1.x/examples/signal-processing"},{"title":"Statistics \u0026 Analysis","href":"/v1.1.x/examples/statistics-analysis"},{"title":"Image Processing","href":"/v1.1.x/examples/image-processing"},{"title":"Data Loading \u0026 I/O","description":"Load and save arrays in .npy, .npz, and text formats across Node.js and browser environments.","href":"/v1.1.x/examples/data-loading"},{"title":"Performance Tips","href":"/v1.1.x/examples/performance-tips"}]}]},{"tab":"Playground","pages":[{"title":"Playground","href":"/v1.1.x/playground"}]}]},{"version":"v1.0.x","pages":[{"title":"v1.0.x","href":"/v1.0.x/examples/performance-tips"}]}]},"basePath":"","title":"Performance Tips - numpy-ts","buildId":"dpl_DeHjVRGfFnhYQwHnfC2pjeXXv8h9","deploymentId":"dpl_DeHjVRGfFnhYQwHnfC2pjeXXv8h9","dynamics":[],"chunks":[]}