Review performance optimization from JavaScript Array

Source: Internet
Author: User
Tags javascript array hasownproperty

JavaScript array deduplication is often used in front-end pen questions. For example, there are arrays var arr = ['A', 'B', 'C', '1', 0, 'C', 1, '', 1, 0]. use JavaScript to deduplicate the unqiue function so that unique (arr) Returns ['A', 'B ', 'C', '1', 0, 1, ''] as a pen test, the test site has two: 1. correct. Don't underestimate this test point. Considering that JavaScript often runs on a browser, it is not easy to ensure the correctness of a function in a variety of browser environments, do not believe that you will continue reading this blog. 2. Performance. Although the JavaScript language itself (in a narrow sense, does not contain extensions such as DOM) in most cases will not cause performance problems, it is unfortunately a question, so the interviewer will still take performance as a test site. Before proceeding, we recommend that you implement a version that you think is the best. Intuitive solution for Array deduplication, as long as the program is written, the first solution can be obtained immediately: function unique (arr) {var ret = [] for (var I = 0; I <arr. length; I ++) {var item = arr [I] if (ret. indexOf (item) ===- 1) {ret. push (item)} return ret} intuition is often very reliable, in modern browsers, the above function is very correct, performance is good. However, the biggest sorrow of the front-end is the challenge of supporting various runtime environments. The indexOf method of the array does not exist in the IE6-8. The intuitive solution should be slightly transformed: var indexOf = []. indexOf? Function (arr, item) {return arr. indexOf (item)}: function indexOf (arr, item) {for (var I = 0; I <arr. length; I ++) {if (arr [I] = item) {return I} return-1} function unique (arr) {var ret = [] for (var I = 0; I <arr. length; I ++) {var item = arr [I] if (indexOf (ret, item) ===-1) {ret. push (item)} return ret} writes to this step. The correctness is correct, but in terms of performance, the two loops will make the interviewer uncomfortable. Optimization solution 1 refers to optimization, which is often a hundred flowers and flowers. But the Eight Immortals are often not grounded, and Baihua is easy to attract bugs. The optimization schemes for Array deduplication are not discussed here. The following describes only one of the most commonly used methods with good results. Function unique (arr) {var ret = [] var hash = {} for (var I = 0; I <arr. length; I ++) {var item = arr [I] var key = typeof (item) + item if (hash [key]! = 1) {ret. the core of push (item) hash [key] = 1} return ret} is to build a hash object to replace indexOf. note that in JavaScript, the key value of an object can only be a string. Therefore, var key = typeof (item) + item must be used to distinguish between value 1 and string '1. But optimization is really easy to bring about. For example, the above implementation cannot judge the following input: 1 unique ([new String (1), new Number (1)]) you can continue to modify the code to ensure good performance and correctness. However, this often leads to poor results. The real demand is written here, so this blog is the topic. Programmers may have some dreams, such as writing universal functions with good general performance. This kind of dream is an important internal drive for programmers to become excellent, but it is easy to get lost without being controlled. Back to performance optimization. There are various Optimizations in the past year, such as core systems, databases, networks, and front-ends. All these optimizations must answer the following question: 1. What are there currently. In what scenarios are optimization and specific restrictions on the scenario. It is important to clarify the limits, which often lead to freedom. 2. What is it. What is the purpose of optimization. Whether to improve stability, increase throughput, or reduce user wait time. Optimization was futile before answering this question. Accurate answers to this question can bring about specific measurable parameters for optimization, so that optimization can have a goal. 3. What can I give up. You cannot have both the fish and the bear's paw. The essence of optimization is the trade-off and trade-offs in specific scenarios. If you don't want to give up anything, optimization will be difficult. This blog is not intended to answer one or more questions. This question is boring. The original driving force for writing this blog is the performance tuning of SeaJS recently. One of the requirements is: define (function (require, exports) {var a = require ('. /A') var B = require ('. /B ')... require ('. /'). fn (...)}) the above is a module. By parsing the function string, we can get the dependent array of the module :['. /','. /B ','. /A']. duplicate fields may appear in the dependency information, so deduplication is required. In this specific scenario, we will answer the above three questions: 1. What is there currently. Some are input restrictions. You only need to consider strings. 2. What is it. This problem is relatively simple, and it is expected that the unique method should be as fast as possible. The metric is to use the Profiles panel in Chrome debugging tool to view the time consumed by the unique method on the specified test page, with the goal of less than 5 ms. 3. What can I give up. You only need to process strings. Other types are not supported. It is often interesting to talk about giving up. This problem is not that simple. Let's talk about it later. Once the solutions under SeaJS are clearly analyzed, the solution is relatively simple: function unique (arr) {var obj = {} forEach (arr, function (item) the code above {obj [item] = 1}) return keys (obj)} depends on forEach and keys. It is inseparable from the context environment (the environment is very important). complete code: util-lang.js above this solution, no matter from the size of the Code, correctness, or a variety of browser comprehensive can come to consider, are very good. Until one day, such a test case occurs: define (function (require, exports) {var a = require ('tostring ') var B = require ('hasownproperties ')...}) in the test case above the "perfect" solution, unique (['tostring', 'hasownproperties']) will be called. // The returned ['tostring ', 'hasownproperties'] IE has a variety of bugs. The following is not very famous but actually exists: var obj = {toString: 1, hasOwnProperty: 1} for (var p in obj) {console. log (p)} In modern browsers, two values are correctly output, but not in Old IE. This is an Internet Explorer enumeration bug: A safer Object. keys compatibility implementation "perfect" solution: var keys = Object. keys | (function () {var hasOwnProperty = Object. prototype. hasOwnProperty, hasDontEnumBug =! {ToString: null }. propertyIsEnumerable ("toString"), DontEnums = ['tostring', 'tolocalstring', 'valueof ', 'hasownproperties', 'isprototypeof', 'propertyisenumerable', 'constructor '], dontEnumsLength = DontEnums. length; return function (o) {if (typeof o! = "Object" & typeof o! = "Function" | o = null) throw new TypeError ("Object. keys called on a non-object "); var result = []; for (var name in o) {if (hasOwnProperty. call (o, name) result. push (name);} www.2cto.com if (hasDontEnumBug) {for (var I = 0; I <DontEnumsLength; I ++) {if (hasOwnProperty. call (o, DontEnums [I]) result. push (DontEnums [I]) ;}} return result ;};}) (); in addition to the DontEnums array, you can also pay special attention to the hasOwnProperty processing method. ** It is not easy for the front-end to ensure "correctness. **

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.