Home Web Front-end JS Tutorial trim prototype function to see the performance of js regular expression_javascript skills

trim prototype function to see the performance of js regular expression_javascript skills

May 16, 2016 pm 06:57 PM
js trim performance regular expression

Generally, the regular writing method is:


[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]

If you encounter big data If you change the length of the string, you will find that this is very resource intensive. It's not very efficient, and sometimes it's even unbearable.

[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]

When explaining the reason I remembered that I saw it mentioned in master regular expression before. There is a difference between the engines of NFA and DFA. js/perl/php/java/.net are all NFA engines.
The difference in mechanism between DFA and NFA has five impacts:
1. DFA only needs to scan each character in the text string once, which is faster but has fewer features; NFA has to eat characters over and over again. Voicing characters is slow, but it has rich features, so it is widely used. Today's main regular expression engines, such as Perl, Ruby, Python's re module, Java and .NET's regex library, are all NFA.
2. Only NFA supports features such as lazy and backreference;
3. NFA is eager to claim credit, so the leftmost subregular expression is matched first, so it occasionally misses the best matching result; DFA It means "the longest left subregular expression is matched first".
4. NFA uses greedy quantifiers by default (that is, for patterns that are "repeated n" times such as /.*/ and /w /, it is carried out in a greedy manner and matches as many characters as possible until it can no longer give up) , NFA will match quantifiers first.
5. NFA may fall into the trap of recursive calls and perform extremely poorly.

backtracking
When NFA finds that it has eaten too much, it spits back one by one, looking for matches while spitting. This process is called backtracking. Due to the existence of this process, during the NFA matching process, especially when writing unreasonable regular expression matching, the text is scanned repeatedly, and the efficiency loss is considerable. Understanding this principle is very helpful for writing efficient regular expressions.

Locate/analyze the reason
When explaining the trim prototype method above. After testing, regardless of whether the results are correct, there are several methods that can resolve the number of echoes of the JS NFA engine
a. Remove the limiting quantifier, that is, change it to Copy code
The code is as follows:


String.prototype.trim = function () {
return this.replace(/^[st] | [st ]$/g, '');
}

b. Remove end-of-string matching. That is, change it to: Copy the code
The code is as follows:


String.prototype.trim = function ( ) {
return this.replace(/^[st ] /g, '');
}

c. Add multi-line matching. That is, change it to: Copy the code
The code is as follows:


String.prototype.trim = function ( ) {
return this.replace(/^[st ] |[st ] $/mg, '');
}
从以上三种改法结合文中开头的NFA资料,我们可以大概的知道trim性能出现问题的原因
量词限定将优先匹配。
量词限定在结尾可能会使JS的正则引擎不停的回朔,出现递归的一个陷阱,这个递归的深度太深。如果字符串更大一点应该会出现栈溢出了。
多行既然能够匹配,而且性能消耗不大。性能上没有任何问题,从一个写这个正则程序的人角度上去看,多行明显比单行要替换的空串多得多。所以第二点的结论应该是对的
改良
首先确定匹配字符串的开始正则是没有任何效率问题的。而匹配结束的时候会出现性能问题,那可以采用正则与传统相结合来改善这个trim性能问题。
例如:

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to validate email address in Golang using regular expression? How to validate email address in Golang using regular expression? May 31, 2024 pm 01:04 PM

To validate email addresses in Golang using regular expressions, follow these steps: Use regexp.MustCompile to create a regular expression pattern that matches valid email address formats. Use the MatchString function to check whether a string matches a pattern. This pattern covers most valid email address formats, including: Local usernames can contain letters, numbers, and special characters: !.#$%&'*+/=?^_{|}~-`Domain names must contain at least One letter, followed by letters, numbers, or hyphens. The top-level domain (TLD) cannot be longer than 63 characters.

The local running performance of the Embedding service exceeds that of OpenAI Text-Embedding-Ada-002, which is so convenient! The local running performance of the Embedding service exceeds that of OpenAI Text-Embedding-Ada-002, which is so convenient! Apr 15, 2024 am 09:01 AM

Ollama is a super practical tool that allows you to easily run open source models such as Llama2, Mistral, and Gemma locally. In this article, I will introduce how to use Ollama to vectorize text. If you have not installed Ollama locally, you can read this article. In this article we will use the nomic-embed-text[2] model. It is a text encoder that outperforms OpenAI text-embedding-ada-002 and text-embedding-3-small on short context and long context tasks. Start the nomic-embed-text service when you have successfully installed o

Performance comparison of different Java frameworks Performance comparison of different Java frameworks Jun 05, 2024 pm 07:14 PM

Performance comparison of different Java frameworks: REST API request processing: Vert.x is the best, with a request rate of 2 times SpringBoot and 3 times Dropwizard. Database query: SpringBoot's HibernateORM is better than Vert.x and Dropwizard's ORM. Caching operations: Vert.x's Hazelcast client is superior to SpringBoot and Dropwizard's caching mechanisms. Suitable framework: Choose according to application requirements. Vert.x is suitable for high-performance web services, SpringBoot is suitable for data-intensive applications, and Dropwizard is suitable for microservice architecture.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

How to match timestamps using regular expressions in Go? How to match timestamps using regular expressions in Go? Jun 02, 2024 am 09:00 AM

In Go, you can use regular expressions to match timestamps: compile a regular expression string, such as the one used to match ISO8601 timestamps: ^\d{4}-\d{2}-\d{2}T \d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$ . Use the regexp.MatchString function to check if a string matches a regular expression.

How to optimize the performance of multi-threaded programs in C++? How to optimize the performance of multi-threaded programs in C++? Jun 05, 2024 pm 02:04 PM

Effective techniques for optimizing C++ multi-threaded performance include limiting the number of threads to avoid resource contention. Use lightweight mutex locks to reduce contention. Optimize the scope of the lock and minimize the waiting time. Use lock-free data structures to improve concurrency. Avoid busy waiting and notify threads of resource availability through events.

What are the performance considerations for C++ static functions? What are the performance considerations for C++ static functions? Apr 16, 2024 am 10:51 AM

Static function performance considerations are as follows: Code size: Static functions are usually smaller because they do not contain member variables. Memory occupation: does not belong to any specific object and does not occupy object memory. Calling overhead: lower, no need to call through object pointer or reference. Multi-thread-safe: Generally thread-safe because there is no dependence on class instances.

How to verify password using regular expression in Go? How to verify password using regular expression in Go? Jun 02, 2024 pm 07:31 PM

The method of using regular expressions to verify passwords in Go is as follows: Define a regular expression pattern that meets the minimum password requirements: at least 8 characters, including lowercase letters, uppercase letters, numbers, and special characters. Compile regular expression patterns using the MustCompile function from the regexp package. Use the MatchString method to test whether the input string matches a regular expression pattern.

See all articles