Utilizzo di variabili con ambito globale
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Mostra come ridurre al minimo l'impronta di memoria delle variabili riutilizzabili sfruttando l'ambito globale.
Per saperne di più
Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:
Esempio di codice
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],[],[],[],null,["# Using global scoped variables\n\nDemonstrate how to minimize the memory footprint of reusable variables by leveraging global scope.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [General development tips](/anthos/run/archive/docs/tips/general)\n- [General development tips](/kubernetes-engine/enterprise/knative-serving/docs/tips/general)\n- [General development tips](/run/docs/tips/general)\n\nCode sample\n-----------\n\n### Go\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // h is in the global (instance-wide) scope.\n var h string\n\n // init runs during package initialization. So, this will only run during an\n // an instance's cold start.\n func init() {\n \th = heavyComputation()\n \tfunctions.HTTP(\"ScopeDemo\", ScopeDemo)\n }\n\n // ScopeDemo is an example of using globally and locally\n // scoped variables in a function.\n func ScopeDemo(w http.ResponseWriter, r *http.Request) {\n \tl := lightComputation()\n \tfmt.Fprintf(w, \"Global: %q, Local: %q\", h, l)\n }\n\n### Java\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import com.google.cloud.functions.HttpFunction;\n import com.google.cloud.functions.HttpRequest;\n import com.google.cloud.functions.HttpResponse;\n import java.io.IOException;\n import java.io.PrintWriter;\n import java.util.Arrays;\n\n public class Scopes implements HttpFunction {\n // Global (instance-wide) scope\n // This computation runs at instance cold-start.\n // Warning: Class variables used in functions code must be thread-safe.\n private static final int INSTANCE_VAR = heavyComputation();\n\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException {\n // Per-function scope\n // This computation runs every time this function is called\n int functionVar = lightComputation();\n\n var writer = new PrintWriter(response.getWriter());\n writer.printf(\"Instance: %s; function: %s\", INSTANCE_VAR, functionVar);\n }\n\n private static int lightComputation() {\n int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n return Arrays.stream(numbers).sum();\n }\n\n private static int heavyComputation() {\n int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n return Arrays.stream(numbers).reduce((t, x) -\u003e t * x).getAsInt();\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const functions = require('@google-cloud/functions-framework');\n\n // TODO(developer): Define your own computations\n const {lightComputation, heavyComputation} = require('./computations');\n\n // Global (instance-wide) scope\n // This computation runs once (at instance cold-start)\n const instanceVar = heavyComputation();\n\n /**\n * HTTP function that declares a variable.\n *\n * @param {Object} req request context.\n * @param {Object} res response context.\n */\n functions.http('scopeDemo', (req, res) =\u003e {\n // Per-function scope\n // This computation runs every time this function is called\n const functionVar = lightComputation();\n\n res.send(`Per instance: ${instanceVar}, per function: ${functionVar}`);\n });\n\n### Python\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import time\n\n import functions_framework\n\n\n # Placeholder\n def heavy_computation():\n return time.time()\n\n\n # Placeholder\n def light_computation():\n return time.time()\n\n\n # Global (instance-wide) scope\n # This computation runs at instance cold-start\n instance_var = heavy_computation()\n\n\n @functions_framework.http\n def scope_demo(request):\n \"\"\"\n HTTP Cloud Function that declares a variable.\n Args:\n request (flask.Request): The request object.\n \u003chttp://flask.pocoo.org/docs/1.0/api/#flask.Request\u003e\n Returns:\n The response text, or any set of values that can be turned into a\n Response object using `make_response`\n \u003chttp://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response\u003e.\n \"\"\"\n\n # Per-function scope\n # This computation runs every time this function is called\n function_var = light_computation()\n return f\"Instance: {instance_var}; function: {function_var}\"\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=cloudrun)."]]