Code optimization method, electronic device, storage medium and program product
By preprocessing the code to be optimized and analyzing the optimization thought chain, the target code optimization strategy is determined, which solves the problem of lack of pertinence in code optimization in the existing technology and achieves code optimization with higher reliability.
Patent Information
- Application Number
- CN202511031557.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-07-25
- Publication Date
- 2025-09-19
- Estimated Expiration
- 2045-07-25
AI Technical Summary
The code optimization methods in the prior art lack specificity, resulting in insufficient reliability of the code optimization results.
By obtaining the code to be optimized, preprocessing is performed to obtain the word segmentation coding sequence, optimization position information and optimization type, the optimization thinking chain is determined, and the target code optimization strategy is determined based on this information to achieve targeted code optimization.
The reliability of code optimization results is improved, ensuring that the optimization direction matches the code function, and improving the accuracy and efficiency of code optimization.
Smart Images

Figure CN120540966B_ABST
Abstract
Description
Technical Field
[0001] The present application relates to the field of computer technology, and in particular to a code optimization method, electronic device, storage medium, and program product. Background Art
[0002] As the scale and complexity of software development continue to increase, code optimization has become a key link in improving software performance, security, and maintainability.
[0003] In related art, conventional code optimization, such as reducing code redundancy, is performed based on large language models. However, because the optimization directions for different functions vary, and the code optimization methods used in related art are not targeted, the reliability of the code optimization results is reduced. Summary of the Invention
[0004] The present application provides a code optimization method, electronic device, storage medium and program product to at least solve the problem in related technologies that the reliability of code optimization results is reduced.
[0005] This application provides a code optimization method, including:
[0006] Get the code to be optimized;
[0007] Preprocess the code to be optimized to obtain the word segmentation code sequence, optimization position information and optimization type corresponding to the code to be optimized;
[0008] Determine an optimization thinking chain for the code to be optimized based on the word segmentation coding sequence, optimization position information, and optimization type corresponding to the code to be optimized; wherein the optimization thinking chain includes multiple optimization steps;
[0009] Determine the target code optimization strategy based on the word segmentation coding sequence, optimization location information, optimization type, and optimization thought chain corresponding to the code to be optimized;
[0010] The code to be optimized is optimized according to the target code optimization strategy to obtain the target optimized code.
[0011] The present application also provides a code optimization device, comprising:
[0012] Acquisition module, used to obtain the code to be optimized;
[0013] The preprocessing module is used to preprocess the code to be optimized to obtain the word segmentation code sequence, optimization position information and optimization type corresponding to the code to be optimized;
[0014] A first determination module is configured to determine an optimization thought chain for the code to be optimized based on the word segmentation code sequence, optimization position information, and optimization type corresponding to the code to be optimized; wherein the optimization thought chain includes multiple optimization steps;
[0015] The second determination module is used to determine the target code optimization strategy based on the word segmentation coding sequence, optimization position information, optimization type and optimization thought chain corresponding to the code to be optimized;
[0016] The optimization module is used to optimize the code to be optimized according to the target code optimization strategy to obtain the target optimized code.
[0017] The present application also provides an electronic device, comprising: a memory for storing a computer program; and a processor for implementing the steps of any of the above-mentioned code optimization methods when executing the computer program.
[0018] The present application also provides a computer-readable storage medium, in which a computer program is stored. When the computer program is executed by a processor, the steps of any of the above-mentioned code optimization methods are implemented.
[0019] The present application also provides a computer program product, including a computer program, which implements the steps of any of the above-mentioned code optimization methods when executed by a processor.
[0020] Through this application, a targeted optimization thinking chain suitable for the code to be optimized is determined based on the word segmentation coding sequence, optimization position information and optimization type of the code to be optimized. Subsequently, the target code optimization strategy for the code to be optimized is determined based on the optimization thinking chain, ensuring that targeted optimization is achieved for the code to be optimized, so that the code optimization direction matches the function of the code to be optimized, thereby improving the reliability of the code optimization results. BRIEF DESCRIPTION OF THE DRAWINGS
[0021] In order to more clearly illustrate the embodiments of the present application, the following is a brief introduction to the drawings required for use in the embodiments. Obviously, the drawings described below are only some embodiments of the present application. For ordinary technicians in this field, other drawings can be obtained based on these drawings without any creative work.
[0022] Figure 1 This is a schematic diagram of the structure of the code optimization system based on the embodiments of the present application;
[0023] Figure 2 A flowchart of a code optimization method provided in an embodiment of the present application;
[0024] Figure 3 A schematic diagram of a training process of a code optimization model provided in an embodiment of the present application;
[0025] Figure 4 A schematic diagram of the training process of another code optimization model provided in an embodiment of the present application;
[0026] Figure 5 A flowchart of an exemplary code optimization method provided in an embodiment of the present application;
[0027] Figure 6 A schematic diagram of the overall process of the code optimization method provided in an embodiment of the present application;
[0028] Figure 7 A schematic diagram of the structure of a code optimization device provided in an embodiment of the present application;
[0029] Figure 8 A schematic diagram of the structure of an electronic device provided in an embodiment of the present application. DETAILED DESCRIPTION
[0030] The following will be combined with the accompanying drawings in the embodiments of this application to clearly and completely describe the technical solutions in the embodiments of this application. Obviously, the embodiments described are only part of the embodiments of this application, not all of them. Based on the embodiments in this application, all other embodiments obtained by ordinary technicians in this field without making creative efforts are within the scope of protection of this application.
[0031] It should be noted that, in the description of this application, the terms "comprises," "includes," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or device comprising a series of elements includes not only those elements, but also other elements not explicitly listed, or elements inherent to such process, method, article, or device. The terms "first," "second," etc., in this application are used to distinguish similar objects, and are not used to describe a particular order or sequence.
[0032] In order to enable those skilled in the art to better understand the present application, the present application is further described in detail below with reference to the accompanying drawings and specific implementation methods.
[0033] As software development continues to grow in scale and complexity, code optimization has become a critical step in improving software performance, security, and maintainability. Large Language Models (LLMs), with their powerful natural language processing and knowledge understanding capabilities, are increasingly being applied to code optimization tasks. They can understand code logic, generate optimization suggestions, and even automatically fix code vulnerabilities. Common methods in the field of code optimization include rule-based optimization and machine learning-assisted optimization, but these approaches have limitations.
[0034] The introduction of large language models has brought new ideas and methods to code optimization. However, its application in code optimization tasks still faces many challenges, such as the accuracy and reliability of optimization results and the lack of effective control over the optimization process.
[0035] In order to solve the above technical problems, the embodiments of the present application provide a code optimization method, electronic device, storage medium and program product, the method comprising obtaining the code to be optimized; preprocessing the code to be optimized to obtain the word segmentation coding sequence, optimization position information and optimization type corresponding to the code to be optimized; determining the optimization thinking chain of the code to be optimized according to the word segmentation coding sequence, optimization position information and optimization type corresponding to the code to be optimized; wherein the optimization thinking chain includes multiple optimization steps; determining the target code optimization strategy according to the word segmentation coding sequence, optimization position information, optimization type and optimization thinking chain corresponding to the code to be optimized; optimizing the code to be optimized according to the target code optimization strategy to obtain the target optimized code. The method provided by the above scheme determines a targeted optimization thinking chain applicable to the code to be optimized according to the word segmentation coding sequence, optimization position information and optimization type of the code to be optimized, and subsequently determines the target code optimization strategy of the code to be optimized according to the optimization thinking chain, ensuring that the code to be optimized is optimized in a targeted manner, so that the code optimization direction matches the function of the code to be optimized, thereby improving the reliability of the code optimization results.
[0036] In conjunction with the specific application environment architecture or specific hardware architecture on which the execution of the code optimization method depends, the specific application environment architecture or specific hardware architecture is described herein.
[0037] First, the structure of the code optimization system on which this application is based is described:
[0038] The code optimization method, electronic device, storage medium and program product provided in the embodiments of the present application are suitable for optimizing the code of functional module development. Figure 1 As shown, it is a structural diagram of the code optimization system based on the embodiment of the present application, which mainly includes a functional module, a data acquisition device and a code optimization device, wherein the functional module can be a data analysis functional module, an encryption calculation functional module or an image data detection functional module, etc. The data acquisition device is used to collect the development code of the functional module and send the collected code as the code to be optimized to the code optimization device, and the code optimization device is used to optimize the code to be optimized to obtain the optimized target optimized code.
[0039] The embodiment of the present application provides a code optimization method for optimizing functional module development code, etc. The execution subject of the embodiment of the present application is an electronic device, such as a server, a desktop computer, a laptop computer, a tablet computer, and other electronic devices that can be used for code optimization.
[0040] like Figure 2 FIG. 1 is a flow chart of a code optimization method provided in an embodiment of the present application, the method comprising:
[0041] Step 201: Obtain the code to be optimized.
[0042] The code to be optimized can be the original code manually edited by the functional module developer to implement the specific functions of the functional module. The original code may contain inefficient structures. Therefore, in order to improve the code quality of the functional module, the code to be optimized can be further optimized based on the code optimization method provided in the embodiment of the application.
[0043] Step 202: pre-process the code to be optimized to obtain the word segmentation code sequence, optimization position information, and optimization type corresponding to the code to be optimized.
[0044] It should be noted that the word segmentation coding sequence is obtained by segmenting the code to be optimized. The optimization position information represents the code range that needs to be optimized, such as lines 5 to 20 of the code to be optimized. The optimization type is used to represent the current defects of the code to be optimized, such as inefficient loops and redundant variables.
[0045] Step 203: Determine the optimization thought chain of the code to be optimized based on the word segmentation code sequence, optimization position information, and optimization type corresponding to the code to be optimized.
[0046] Among them, the optimization thinking chain includes multiple optimization steps.
[0047] Specifically, the optimization steps of the optimization chain are divided into at least problem identification, strategy selection, and solution generation. For example, if the optimization type is loop inefficiency, the optimization chain includes the following optimization steps: identifying the loop type, applying the arithmetic sequence summation formula to optimize the code, and verifying the calculation results. Problem identification is determined based on the word segmentation code sequence and optimization location information, while strategy selection and solution generation are further determined based on the optimization type.
[0048] Step 204 : Determine the target code optimization strategy based on the word segmentation coding sequence, optimization position information, optimization type, and optimization thought chain corresponding to the code to be optimized.
[0049] Specifically, the cross-attention mechanism can be used to infer the target code optimization strategy by taking the word segmentation coding sequence, optimization position information, optimization type and optimization thinking chain corresponding to the code to be optimized as input.
[0050] Step 205 : Optimize the code to be optimized according to the target code optimization strategy to obtain the target optimized code.
[0051] Specifically, the code to be optimized may be first converted into a code abstract syntax tree, and then the code abstract syntax tree may be optimized according to a target code optimization strategy, thereby obtaining an optimized target optimized code.
[0052] Based on the above embodiment, as an implementable method, in one embodiment, the code to be optimized is preprocessed to obtain the word segmentation encoding sequence, optimization position information and optimization type corresponding to the code to be optimized, including:
[0053] Step 2021: perform word segmentation processing on the code to be optimized to obtain a word segmentation code sequence corresponding to the code to be optimized;
[0054] Step 2022: Perform static analysis on the code to be optimized to obtain optimization location information and optimization type of the code to be optimized.
[0055] Among them, preprocessing includes word segmentation and static analysis.
[0056] Specifically, word segmentation involves breaking the code to be optimized into multiple independent words or symbol units according to specific rules. These units form a word segmentation encoding sequence. Static analysis analyzes the structure and characteristics of the code without executing it, thereby determining the optimization location information and optimization type of the code to be optimized.
[0057] Among them, the preprocessing method provided in the embodiment of the present application is conducive to improving the accuracy and efficiency of code optimization, reducing the processing of unnecessary code parts during the optimization process, and performing targeted optimization on key optimization positions and types, ensuring targeted optimization of the code to be optimized, so that the code optimization direction matches the function of the code to be optimized, thereby improving the reliability of the code optimization results.
[0058] Specifically, in one embodiment, the code to be optimized can be segmented with characters as the smallest segmentation unit to obtain a segmentation sequence of the code to be optimized; according to the frequency of occurrence of each adjacent segmentation pair in the segmentation sequence, the adjacent segmentation pairs with the highest frequency of occurrence are merged into new segmentations to obtain a new segmentation sequence; return to the step of merging the adjacent segmentations with the highest frequency of occurrence into new segmentations to obtain a new segmentation sequence according to the frequency of occurrence of each adjacent segmentation pair in the segmentation sequence, until the new segmentation sequence obtained meets the preset iteration condition; when the new segmentation sequence meets the preset iteration condition, the new segmentation sequence is used as the segmentation encoding sequence corresponding to the code to be optimized.
[0059] The word segmentation process provided in this embodiment can segment code using a byte pair encoding (BPE) algorithm, implemented using the Python sentencepiece library. This algorithm breaks long identifiers into high-frequency sub-tokens (e.g., calculateAverage → calculate+Average), building a code dictionary containing over 60,000 tokens. Tokens are word segments, and the code dictionary is the word segmentation encoding sequence.
[0060] Specifically, by first performing a preliminary segmentation of the code using characters as the smallest segmentation unit, the basic components of the code can be analyzed comprehensively and meticulously. On this basis, based on the frequency of occurrence of each adjacent segmentation pair in the segmentation sequence, the adjacent segmentation pairs with the highest frequency of occurrence are merged into new segmentations, thereby obtaining a new segmentation sequence. This merging operation helps to identify common combination patterns in the code. By continuously repeating this merging step until the new segmentation sequence meets the preset iteration conditions, the segmentation sequence at this time can more accurately reflect the structure and semantic information of the code, and therefore it is used as the segmentation encoding sequence corresponding to the code to be optimized.
[0061] The preset iteration conditions include that the length of the word segmentation sequence reaches a preset length threshold or the number of merge repetitions reaches a preset number threshold.
[0062] Specifically, in one embodiment, the code to be optimized can be statically analyzed to obtain the code syntax structure, code execution path, and variable value transfer path of the code to be optimized; based on the code syntax structure, code execution path, and variable value transfer path of the code to be optimized, the optimization location information and optimization type of the code to be optimized can be determined.
[0063] Among them, the static analysis in the embodiment of the present application can be based on the integrated CodeQL static analysis tool, which identifies the optimization points (optimization location information) in the code through predefined rules (such as cyclomatic complexity threshold, memory leak pattern), and generates the optimization location label corresponding to the optimization point. <optstart> / <optend>, optimization tags (optimization types) include loop_inefficiency (loop inefficiency), redundant_variable (redundant variable), etc.
[0064] Specifically, by performing syntax analysis on the code, the grammatical structure of the code can be determined, and the composition and relationship of each grammatical element in the code can be clarified, which helps to discover potential syntax errors or irregularities in the code. At the same time, by analyzing the code execution path and the variable value transfer path, it is possible to understand the execution process of the code under different conditions and the changes in the transfer of variable values in the program. Based on these analysis results, it is possible to accurately determine the location information that needs to be optimized in the code, such as which code blocks have low execution efficiency, which variable transfer methods may cause performance bottlenecks, etc. In addition, the corresponding optimization type can also be determined, such as optimization for algorithm complexity, optimization for resource utilization efficiency, and optimization for code readability.
[0065] Based on the above embodiment, as an implementable method, in one embodiment, according to the word segmentation encoding sequence, optimization position information and optimization type corresponding to the code to be optimized, the optimization thinking chain of the code to be optimized is determined, including:
[0066] Step 2031: Generate a semantic vector of the code to be optimized based on the word segmentation code sequence, optimization position information, and optimization type corresponding to the code to be optimized;
[0067] Step 2032: determining the first optimization step of the code to be optimized based on the semantic vector of the code to be optimized;
[0068] Step 2033 , adding the first optimization step as a sequence head to the determined step sequence;
[0069] Step 2034: Determine the next optimization step based on the semantic vector of the code to be optimized and the determined step sequence;
[0070] Step 2035: Add the next optimization step to the determined step sequence in order, and return to the step of determining the next optimization step based on the semantic vector of the code to be optimized and the determined step sequence, until the determined step sequence obtained satisfies the preset optimization thought chain constraint conditions;
[0071] Step 2036: When the determined step sequence meets the preset optimization thinking chain constraint conditions, the determined step sequence is used as the optimization thinking chain.
[0072] It should be noted that in the embodiments of this application, the optimization thinking chain can be determined based on a pre-trained code optimization model. For the training of the code optimization model, the training data (original code) is directly used for pre-training and fine-tuning of the model to ensure that the model learns the mapping relationship between "defects-strategies-changes". Input format: concatenate [segmentation code sequence] [position label] [optimization type], such as [for i in range(n): sum += i <optstart>loop_inefficiency <optend>][Optimize cycle efficiency].
[0073] Model output pairs include:
[0074] Chain of Thought (CoT): Serializes optimization steps, such as ["identify loop type", "apply arithmetic progression sum formula", "verify calculation results"], "the current loop time complexity is O (n), which can be optimized to O (1) using the arithmetic progression formula"). Chain of Thought can ensure that each code change has a logical basis.
[0075] Code optimization strategy: retain the word sequence of the original code structure, such as sum = n×(n+1) / / 2 <optend>.
[0076] Since the existing training data is limited, data augmentation technology can be used to expand the training data. For example, the tree-sitter library is used to perform code mutation, and loop expansion, variable renaming, etc. are used to generate 3 times the data, covering 200+ optimization modes. Figure 3 As shown in FIG, a training flow diagram of a code optimization model provided in an embodiment of the present application is shown, Figure 3 The process shown is used to prepare the training data for the model.
[0077] It should be further explained that the code optimization model adopts a layered encoder-decoder architecture, based on CodeT5-base (220M parameters), to build a dual-branch model, which learns the joint representation of code semantics and optimization logic through the encoder-decoder architecture. The model loss function uses the cross entropy loss function, and the architecture quantifies the thought chain generated by the model by defining the corresponding loss function ( ) and optimized code The error from the true sequence guides model parameter updates, bringing the generated results closer to the standard optimization logic and code changes. The model outputs a token-level probability distribution. Cross-entropy is a standard method for measuring the difference between this distribution and the true label (standard thought chain / code). It is a standard loss function for generation tasks such as NLP and code generation, ensuring that the accuracy of optimization logic and code changes is quantifiable and optimizable. Both code and thought chains are discrete token sequences, making cross-entropy naturally suitable for multi-class probabilistic prediction. The cross-entropy loss function quantifies the generation error of discrete sequences, providing an efficient optimization target for the model. It is the core technical support for achieving "thought chain-code" semantic alignment and improving generation quality.
[0078] The decoder is used to capture the code's grammatical structure (such as loops and conditionals) and semantic information (such as variable usage and algorithmic logic). The decoder input is: [word segmentation encoding sequence] [position label] [optimization type]. The code semantics and position information are captured through a 12-layer Transformer. Each layer contains a 12-head self-attention mechanism and supports a maximum input of 1024 tokens. The output is: a context vector H∈R^(m×768), where m is the number of input tokens (the length of the word segmentation encoding sequence). The context vector is the semantic vector.
[0079] The decoder consists of two branches: the thought chain branch and the code generation branch (code optimization strategy branch). The goal of the thought chain branch is to maximize the sequence probability of the thought chain steps and ensure logical coherence. The input for the decoder training of the thought chain branch is: Special Tokens" <cot>"; Output: Optimization step sequence ,Causal Mask is used to ensure the order of steps, where the optimized step sequence is the determined step sequence and also the optimized thinking chain.
[0080] Loss function:
[0081] in, represents the first loss, is the length of the thought chain, For the Token of the optimization step, Generate the first The probability of an optimization step represents the decoder's "confidence vote" on the thought chain step. Through training and optimization, each step generated by the model is strongly associated with the code semantics and the preceding logic, providing an explainable logical basis for subsequent confidence evaluation and code optimization. The above loss function is used to measure the degree of fit between the thought chain sequence generated by the model and the standard optimization step. By minimizing , the model learns how to generate optimization ideas with logical coherence and clear steps, ensuring the rationality and explainability of the thinking chain.
[0082] Specifically, the embodiment of the present application generates semantic vectors of the code to be optimized based on the encoder, and determines the optimized thought chain based on the thought chain branch of the decoder. Since the thought chain branch uses a causal mask in the process of determining the optimized thought chain, the generation of each optimization step in the process of determining the optimized thought chain by the decoder can only rely on the previous step, forcing it to follow the logical order of problem location, strategy selection, and solution generation, avoiding step reversal or jump, thereby ensuring the orderliness of the thought chain.
[0083] Based on the above embodiment, as an implementable approach, in one embodiment, a target code optimization strategy is determined based on the word segmentation encoding sequence, optimization position information, optimization type, and optimization thought chain corresponding to the code to be optimized, including:
[0084] Step 2041: Generate a semantic vector of the code to be optimized based on the word segmentation code sequence, optimization position information, and optimization type corresponding to the code to be optimized;
[0085] Step 2042, determining an optimized thinking chain vector according to the optimized thinking chain;
[0086] Step 2043: combining the semantic vector and the optimized thought chain vector into a target optimization vector;
[0087] Step 2044: Determine multiple candidate code optimization strategies based on the target optimization vector;
[0088] In step 2045 , the candidate code optimization strategy with the highest comprehensive confidence among the multiple candidate code optimization strategies is used as the target code optimization strategy.
[0089] Specifically, the target code optimization strategy can be determined based on the code optimization strategy branch of the decoder. The purpose of the code optimization strategy branch of the decoder is to ensure that the generated code is consistent with the optimization logic described by the thought chain. In the process of training the code optimization strategy branch, the input includes the semantic vector and optimized thinking chain vector , the output is optimized code segmentation (code optimization strategy) ,Introducing cross-attention to align thinking chains with code changes.
[0090] Loss function:
[0091] in, represents the second loss, To optimize code length, For the Optimization tokens, (code word segmentation) is the vector representation of the thought chain. Generate the first The probability of an optimized code token is the core quantitative metric used by the MindChain logic to guide code generation, ensuring that the optimized code both conforms to the original semantics and follows the explicit reasoning steps. The aforementioned loss function is used to constrain the optimized code generated by the model to be consistent with the MindChain description logic, rather than arbitrarily changing the code.
[0092] Specifically, in one embodiment, the candidate code optimization strategy whose comprehensive confidence reaches a preset threshold can be used as the candidate code optimization strategy; when the candidate code optimization strategy is not unique, the candidate code optimization strategy with the highest comprehensive confidence among the candidate code optimization strategies is used as the target code optimization strategy.
[0093] It should be noted that the decoder can generate five sets of differentiated solutions through a search (beam_size=5), that is, generate multiple candidate code optimization strategies in parallel. For example, for loop optimization, it can generate different strategies such as "formula replacement," "vectorized operations," and "caching intermediate results" to cover diverse needs. The comprehensive confidence level is used to characterize the accuracy and reliability of each candidate code optimization strategy. Candidate code optimization strategies with a comprehensive confidence level that reaches the preset threshold have achieved the minimum accuracy and reliability standards for code optimization. Therefore, if there is no unique candidate code optimization strategy, the candidate with the highest comprehensive confidence level will be selected as the target code optimization strategy to ensure that the final target code optimization strategy has the highest accuracy and reliability.
[0094] Specifically, if Figure 4 This is a schematic diagram of the training process of another code optimization model provided in an embodiment of the present application. The pre-training stage of the code optimization model provided in an embodiment of the present application: performing tasks such as masked language modeling (MLM) and code summary generation on the CodeSearchNet dataset, and learning code structure and semantic associations.
[0095] Fine-tuning phase: Trained on an optimization task dataset, the input contains over 130,000 labeled code segments, and outputs alignment data between thought chains and optimized code to strengthen the "logic-to-code" mapping capability.
[0096] Input: [word segmentation encoding sequence][position label][optimization type] triple.
[0097] Output: forced aligned thought chain - optimized code pair, the optimized code is the code optimization strategy.
[0098] Joint training loss function: .
[0099] The joint training loss function optimizes both the thought chain and code generation branches through a weighted summation. This allows the model to focus on both logical reasoning (thought chain) and actual code changes (optimized code) during training, improving the semantic alignment and overall quality of the two. The double-branch loss balance coefficient is set to 0.8 by default (code generation takes precedence over thought chaining). This improves the guiding role of thought chaining in code generation and avoids illogical changes.
[0100] Based on the above embodiments, Figure 5 FIG. 1 is a flow chart of an exemplary code optimization method provided in an embodiment of the present application. As an implementable manner, in one embodiment, the method further includes:
[0101] Step 301: for any code optimization strategy to be selected, determine the reliability index of the code optimization strategy to be selected based on the word segmentation information of the code optimization strategy to be selected;
[0102] Step 302: determining the consistency index of the code optimization strategy to be selected based on the thought chain information of the code optimization strategy to be selected;
[0103] Step 303: Determine the rationality index of the code optimization strategy to be selected based on the code change information of the code optimization strategy to be selected;
[0104] Step 304 : determining the comprehensive confidence level of the candidate code optimization strategy based on the reliability index, consistency index, and rationality index of the candidate code optimization strategy.
[0105] The reliability metric characterizes the credibility of a candidate code optimization strategy; the consistency metric characterizes the degree of alignment between the candidate strategy's optimization thought chain and the standard thought chain; and the rationality metric characterizes the rationality of the code modification applied by the candidate strategy. The comprehensive confidence level is a comprehensive evaluation metric for the candidate code optimization strategy, combining the reliability, consistency, and rationality metrics. This application designs a three-dimensional confidence evaluation system (reliability, consistency, and rationality) and combines it with a joint loss function and a dynamic screening strategy to systematically quantify the quality of optimization solutions. This effectively suppresses radical changes and low-quality code generation, improving the controllability and execution efficiency of code optimization.
[0106] Specifically, in one embodiment, the reliability index of the code optimization strategy to be selected may be determined based on the following formula:
[0107]
[0108] in, Represents the reliability index of the candidate code optimization strategy, Indicates the number of word segments of the target optimized code obtained by optimizing the optimized code according to the selected code optimization strategy. Indicates that when the target optimization vector and the preceding word segmentation are determined, the first The participle is The probability of represents the semantic vector, Represents the optimized thought chain vector.
[0109] Specifically, Also known as the reliability index of the code optimization model, the higher the average logarithmic probability value of the generated code of the selected code optimization strategy, the more accurate and reliable the model output is. For the decoder The logarithmic probability of generating a token (word segment) is obtained through model training. The specific calculation relies on the self-attention mechanism of the Transformer decoder, which dynamically associates the input code semantics with the historical generation steps, outputs the probability value of each possible step, and then normalizes it through the softmax function.
[0110] Specifically, in one embodiment, the consistency index of the code optimization strategy to be selected may be determined based on the following formula:
[0111]
[0112] in, Represents the consistency index of the candidate code optimization strategy, Indicates the optimization thinking chain corresponding to the selected code optimization strategy, Indicates the standard thinking chain, Indicates the longest common subsequence length of the optimized thinking chain and the standard thinking chain, Indicates optimizing the length of the thinking chain, Indicates the length of the standard thinking chain.
[0113] Specifically, This metric, also known as the logical consistency index, measures the semantic similarity between the optimized and standard thought chains, based on the ROUGE-L metric, to ensure the rationality of the optimization logic. Higher values indicate more rational logic. The standard thought chain includes conventional optimization steps for code that implements the same functionality as the code to be optimized.
[0114] Specifically, in one embodiment, the rationality index of the code optimization strategy to be selected may be determined based on the following formula:
[0115]
[0116] in, Indicates the rationality index of the candidate code optimization strategy, Indicates the number of changed lines of code to be optimized by the selected code optimization strategy. Indicates the original number of lines of code to be optimized.
[0117] Specifically, the rationality index, also known as the change rationality index, is used to suppress excessive changes. The closer the value is to 1, the more conservative and reasonable the change is.
[0118] Specifically, in one embodiment, the comprehensive confidence of the code optimization strategy to be selected may be determined based on the following formula:
[0119]
[0120] in, Represents the comprehensive confidence of the candidate code optimization strategy, Represents the reliability index of the candidate code optimization strategy, Represents the consistency index of the candidate code optimization strategy, Indicates the rationality index of the candidate code optimization strategy, 、 and Indicates the preset weight coefficient.
[0121] Specifically, the weight coefficients are set based on the optimization objectives (e.g., the importance of reliability, consistency, and rationality). The confidence weight parameters (0.5, 0.3, and 0.2) balance the reliability, consistency, and rationality indicators and can be dynamically adjusted based on the scenario, with the optimal ratio determined through experiments.
[0122] Specifically, in one embodiment, the weight coefficient can be dynamically adjusted based on the code function type, optimization location information, and optimization type of the code to be optimized. For example, for performance-sensitive code, the reliability index weight coefficient a is increased; for security-sensitive code, the consistency index weight coefficient b is increased, and so on. By dynamically assigning weights to different scenarios, the lack of adaptability of fixed weights to special scenarios is avoided. For example, for embedded system code (sensitive to resource usage), the weight of the rationality index can be increased, and strategies with fewer lines of change can be given priority; for algorithm library code (sensitive to logical correctness), the weight coefficient of the consistency index can be increased to ensure that the optimization logic matches the standard approach.
[0123] Specifically, for the multiple candidate code optimization strategies obtained, first retain Otherwise, adjust the beam search parameters (such as increasing beam_size) to trigger model regeneration or push to IDE for developer review. That is, when the candidate code optimization strategy is empty, regenerate the code optimization strategy or manually intervene. For example, if a candidate code optimization strategy 、 、 ,but , are retained and used as candidate code optimization strategies. Figure 6 As shown in FIG, it is a schematic diagram of the overall process of the code optimization method provided in the embodiment of the present application, as shown in FIG. Figure 6 The method shown is as follows Figure 2 The method shown is an exemplary embodiment, and the implementation principles of the two are the same and will not be described in detail.
[0124] The code optimization method provided by the embodiment of the present application is obtained by obtaining the code to be optimized; pre-processing the code to be optimized to obtain the word segmentation coding sequence, optimization position information and optimization type corresponding to the code to be optimized; determining the optimization thinking chain of the code to be optimized according to the word segmentation coding sequence, optimization position information and optimization type corresponding to the code to be optimized; wherein, the optimization thinking chain includes multiple optimization steps; determining the target code optimization strategy according to the word segmentation coding sequence, optimization position information, optimization type and optimization thinking chain corresponding to the code to be optimized; optimizing the code to be optimized according to the target code optimization strategy to obtain the target optimized code. The method provided by the above scheme determines the targeted optimization thinking chain applicable to the code to be optimized according to the word segmentation coding sequence, optimization position information and optimization type of the code to be optimized, and subsequently determines the target code optimization strategy of the code to be optimized according to the optimization thinking chain, ensuring that the code to be optimized is optimized in a targeted manner, so that the code optimization direction matches the function of the code to be optimized, thereby improving the reliability of the code optimization result. Moreover, by constructing a code optimization framework guided by thinking chain and confidence, the interpretability, high quality and efficiency of the code optimization process are achieved. By integrating an encoder-decoder architecture with multi-dimensional confidence assessment, and integrating a comprehensive process of data preprocessing, model training, solution generation, and dynamic screening, this approach reduces the black-box nature of code optimization reasoning and the blindness of changes, while improving the reliability and maintainability of optimization results. The optimization process is divided into key steps, including data preprocessing, model training, solution generation, and confidence screening. Based on the Transformer architecture's dual-branch model and beam search technology, this approach uses explicit reasoning through thought chains to cover more optimization paths when diverse optimization needs arise, generating multiple sets of candidate code optimization solutions and enhancing the comprehensiveness and adaptability of code optimization.
[0125] Through the description of the above implementation methods, those skilled in the art can clearly understand that the method according to the above embodiment can be implemented by means of software plus the necessary general hardware platform, and of course it can also be implemented by hardware, but in many cases the former is a better implementation method.
[0126] The embodiments of the present application also provide a code optimization device for executing the code optimization method provided in the above embodiments.
[0127] like Figure 7 FIG. 7 is a schematic diagram of the structure of a code optimization device according to an embodiment of the present invention. The code optimization device 70 includes an acquisition module 701 , a pre-processing module 702 , a first determination module 703 , a second determination module 704 and an optimization module 705 .
[0128] Among them, the acquisition module is used to obtain the code to be optimized; the preprocessing module is used to preprocess the code to be optimized to obtain the word segmentation coding sequence, optimization position information and optimization type corresponding to the code to be optimized; the first determination module is used to determine the optimization thinking chain of the code to be optimized according to the word segmentation coding sequence, optimization position information and optimization type corresponding to the code to be optimized; wherein the optimization thinking chain includes multiple optimization steps; the second determination module is used to determine the target code optimization strategy according to the word segmentation coding sequence, optimization position information, optimization type and optimization thinking chain corresponding to the code to be optimized; the optimization module is used to optimize the code to be optimized according to the target code optimization strategy to obtain the target optimized code.
[0129] For the description of the features in the embodiment corresponding to the code optimization device, please refer to the relevant description of the embodiment corresponding to the code optimization method, and no further details will be given here.
[0130] The embodiment of the present application also provides an electronic device, such as Figure 8 As shown, it is a structural diagram of an electronic device provided in an embodiment of the present application, including a processor 10 and a memory 20, wherein a computer program is stored in the memory 20, and the processor 10 is configured to run the computer program to execute the steps in any one of the above-mentioned code optimization method embodiments.
[0131] An embodiment of the present application further provides a computer-readable storage medium, in which a computer program is stored, wherein the computer program is configured to execute the steps of any of the above-mentioned code optimization method embodiments when running.
[0132] In an exemplary embodiment, the computer-readable storage medium may include, but is not limited to, various media that can store computer programs, such as a USB flash drive, a read-only memory (ROM), a random access memory (RAM), a mobile hard disk, a magnetic disk, or an optical disk.
[0133] An embodiment of the present application further provides a computer program product, which includes a computer program. When the computer program is executed by a processor, the steps in any of the above code optimization method embodiments are implemented.
[0134] An embodiment of the present application further provides another computer program product, including a non-volatile computer-readable storage medium, wherein the non-volatile computer-readable storage medium stores a computer program, and when the computer program is executed by a processor, the steps in any of the above-mentioned code optimization method embodiments are implemented.
[0135] Professionals may further appreciate that the units and algorithm steps of each example described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, computer software, or a combination of the two. In order to clearly illustrate the interchangeability of hardware and software, the above description has generally described the components and steps of each example according to their functions. Whether these functions are performed in hardware or software depends on the specific application and design constraints of the technical solution. Professionals and technicians may use different methods to implement the described functions for each specific application, but such implementation should not be considered beyond the scope of this application.
[0136] The above is a detailed introduction to a code optimization method, electronic device, storage medium, and program product provided by the present application. Specific examples are used herein to illustrate the principles and implementation methods of the present application. The description of the above embodiments is only used to help understand the method and core ideas of the present application. It should be pointed out that, for those skilled in the art, without departing from the principles of the present application, several improvements and modifications can be made to the present application, and these improvements and modifications also fall within the scope of protection of the claims of the present application.< / cot> < / optend> < / optend> < / optstart> < / optend> < / optstart>
Claims
1. A code optimization method, characterized in that: include: Get the code to be optimized; Preprocessing the code to be optimized to obtain a word segmentation coding sequence, optimization position information, and optimization type corresponding to the code to be optimized; Determine an optimization thought chain for the code to be optimized based on the word segmentation code sequence, optimization position information, and optimization type corresponding to the code to be optimized; wherein the optimization thought chain includes multiple optimization steps; Determine the target code optimization strategy based on the word segmentation coding sequence, optimization position information, optimization type and optimization thought chain corresponding to the code to be optimized; Optimizing the code to be optimized according to the target code optimization strategy to obtain a target optimized code; The preprocessing of the code to be optimized to obtain the word segmentation coding sequence, optimization position information and optimization type corresponding to the code to be optimized includes: Performing word segmentation processing on the code to be optimized to obtain a word segmentation encoding sequence corresponding to the code to be optimized; Performing static analysis on the code to be optimized to obtain optimization location information and optimization type of the code to be optimized; Wherein, the preprocessing includes the word segmentation processing and static analysis; The step of determining an optimization thought chain for the code to be optimized based on the word segmentation coding sequence, optimization position information, and optimization type corresponding to the code to be optimized includes: Generate a semantic vector of the code to be optimized according to the word segmentation encoding sequence, optimization position information and optimization type corresponding to the code to be optimized; Determining a first optimization step of the code to be optimized according to the semantic vector of the code to be optimized; adding the first optimization step as a sequence head to the determined step sequence; Determining the next optimization step according to the semantic vector of the code to be optimized and the determined step sequence; Adding the next optimization step to the determined step sequence in sequence, and returning to the step of determining the next optimization step according to the semantic vector of the code to be optimized and the determined step sequence, until the obtained determined step sequence satisfies the preset optimization thinking chain constraint condition; When the determined step sequence meets the preset optimization thinking chain constraint condition, the determined step sequence is used as the optimization thinking chain; The target code optimization strategy is determined according to the word segmentation coding sequence, optimization position information, optimization type and optimization thought chain corresponding to the code to be optimized, including: Generate a semantic vector of the code to be optimized according to the word segmentation encoding sequence, optimization position information and optimization type corresponding to the code to be optimized; Determining an optimized thinking chain vector according to the optimized thinking chain; Combining the semantic vector and the optimized thought chain vector into a target optimization vector; Determining a plurality of candidate code optimization strategies according to the target optimization vector; The candidate code optimization strategy with the highest comprehensive confidence among the multiple candidate code optimization strategies is used as the target code optimization strategy.
2. The code optimization method according to claim 1, characterized in that: The word segmentation processing of the code to be optimized to obtain the word segmentation coding sequence corresponding to the code to be optimized includes: Taking characters as the smallest word segmentation unit, the code to be optimized is segmented to obtain a word segmentation sequence of the code to be optimized; According to the frequency of occurrence of each adjacent word pair in the word sequence, the adjacent word pairs with the highest frequency of occurrence are merged into new word pairs to obtain a new word sequence; Returning to the step of merging the adjacent segmentation pairs with the highest occurrence frequency into new segmentation pairs according to the occurrence frequencies of the adjacent segmentation pairs in the segmentation sequence to obtain a new segmentation sequence, until the obtained new segmentation sequence meets the preset iteration condition; When the new word segmentation sequence meets the preset iteration condition, the new word segmentation sequence is used as the word segmentation encoding sequence corresponding to the code to be optimized.
3. The code optimization method according to claim 1, wherein: The static analysis of the code to be optimized to obtain the optimization location information and optimization type of the code to be optimized includes: Performing static analysis on the code to be optimized to obtain the code syntax structure, code execution path, and variable value transfer path of the code to be optimized; The optimization location information and optimization type of the code to be optimized are determined according to the code syntax structure, code execution path and variable value transfer path of the code to be optimized.
4. The code optimization method according to claim 1, wherein: The step of selecting the candidate code optimization strategy with the highest comprehensive confidence among the multiple candidate code optimization strategies as the target code optimization strategy includes: The candidate code optimization strategies whose comprehensive confidence reaches a preset threshold are used as candidate code optimization strategies; In the case that the candidate code optimization strategy is not unique, the candidate code optimization strategy with the highest comprehensive confidence among the candidate code optimization strategies is used as the target code optimization strategy.
5. The code optimization method according to claim 1, wherein: The method further comprises: For any of the candidate code optimization strategies, determining a reliability index of the candidate code optimization strategy based on the word segmentation information of the candidate code optimization strategy; Determining a consistency index of the candidate code optimization strategy based on the thought chain information of the candidate code optimization strategy; Determining a rationality index of the candidate code optimization strategy based on the code change information of the candidate code optimization strategy; The comprehensive confidence level of the candidate code optimization strategy is determined based on the reliability index, consistency index and rationality index of the candidate code optimization strategy.
6. The code optimization method according to claim 5, characterized in that: The step of determining the reliability index of the candidate code optimization strategy based on the word segmentation information of the candidate code optimization strategy includes: The reliability index of the candidate code optimization strategy is determined based on the following formula: in, represents the reliability index of the candidate code optimization strategy, represents the number of word segments of the target optimized code obtained by optimizing the code to be optimized according to the selected code optimization strategy, Indicates that when the target optimization vector and the preceding word segmentation are determined, the first The participle is The probability of represents the semantic vector, Represents the optimized thought chain vector.
7. The code optimization method according to claim 5, characterized in that: The step of determining the consistency index of the candidate code optimization strategy based on the thought chain information of the candidate code optimization strategy includes: The consistency index of the candidate code optimization strategy is determined based on the following formula: in, represents the consistency index of the candidate code optimization strategy, Indicates the optimization thinking chain corresponding to the candidate code optimization strategy, Indicates the standard thinking chain, represents the longest common subsequence length of the optimized thinking chain and the standard thinking chain, represents the length of the optimization thought chain, Indicates the length of the standard thinking chain.
8. The code optimization method according to claim 5, characterized in that: The determining, based on the code change information of the candidate code optimization strategy, a rationality index of the candidate code optimization strategy includes: The rationality index of the candidate code optimization strategy is determined based on the following formula: in, represents the rationality index of the candidate code optimization strategy, Indicates the number of changed lines of the code to be optimized by the selected code optimization strategy, Indicates the original number of lines of code to be optimized.
9. The code optimization method according to claim 5, characterized in that: Determining the comprehensive confidence of the candidate code optimization strategy based on the reliability index, consistency index, and rationality index of the candidate code optimization strategy includes: The comprehensive confidence of the candidate code optimization strategy is determined based on the following formula: in, represents the comprehensive confidence of the candidate code optimization strategy, represents the reliability index of the candidate code optimization strategy, represents the consistency index of the candidate code optimization strategy, represents the rationality index of the candidate code optimization strategy, 、 and Indicates the preset weight coefficient.
10. An electronic device, characterized in that: include: memory for storing computer programs; A processor, configured to implement the steps of the code optimization method according to any one of claims 1 to 9 when executing the computer program.
11. A computer-readable storage medium, characterized in that The computer-readable storage medium stores a computer program, wherein the computer program, when executed by a processor, implements the steps of the code optimization method according to any one of claims 1 to 9.
12. A computer program product comprising a computer program, characterized in that When the computer program is executed by a processor, the steps of the code optimization method according to any one of claims 1 to 9 are implemented.
Citation Information
Patent Citations
JavaScript code optimization method based on front-end byte code technology
CN110399133A
Program optimization method, device, electronic device and storage medium
CN119759327A