Strings in JavaScript

"Պրիմիտիվներ, որոնք օժտված են օբյեկտների գերունակություններով։"

Primitive String

Տեքստային պրիմիտիվ տվյալ, որը պահվում է Stack հիշողության մեջ։

Autoboxing

Ժամանակավոր Wrapper Օբյեկտի ստեղծում։

Immutability

Անփոփոխելիություն. տեքստը չի կարող փոփոխվել։

JavaScript-ում տեքստ ստեղծելու երկու ձև կա։

let strPrimitive = "Hello";
let strObject = new String("Hello");

Կարևոր կանոն. Մի՛ օգտագործեք new String():

Ինչպե՞ս ենք կանչում մեթոդներ պրիմիտիվների վրա։

graph LR A[Primitive String] -- ".toUpperCase()" --> B[Wrapper Object] B -- "Execute" --> C[Result String] C --> D[GC Delete Wrapper] style B fill:transparent,stroke:#f7df1e style C fill:#f7df1e,color:#000

Այդ պահին JavaScript-ը կատարում է Autoboxing:

JavaScript-ում String-ները ամբողջությամբ անփոփոխելի են։

let text = "JavaScript";
text[0] = "Y"; // does nothing

Ցանկացած մեթոդ ստեղծում է նոր տեքստ։

String Interning (String Pool)

V8 շարժիչի օպտիմալացումները։

graph TD subgraph Stack [Stack Memory] S1[str1 = 'JS'] S2[str2 = 'JS'] S3[str3 = 'JS'] end subgraph Heap [Heap Memory] Pool[String Pool: 'JS'] end S1 --> Pool S2 --> Pool S3 --> Pool style Pool fill:#1e1e1e,stroke:#f7df1e,stroke-width:2px,color:#fff style Stack fill:#1e1e1e,stroke:#777,color:#fff style Heap fill:#1e1e1e,stroke:#2196f3,color:#fff style S1 fill:#2d2d2d,stroke:#555,color:#fff style S2 fill:#2d2d2d,stroke:#555,color:#fff style S3 fill:#2d2d2d,stroke:#555,color:#fff

Իդենտիկ տեքստերը կիսում են միևնույն հասցեն։

Ամենակարևոր մեթոդները։

slice(), includes(), trim(), etc.

Կոնկատենացիան ցիկլերի մեջ։

// Concatenation performance example

Լուծումը՝ օգտագործել Array.join()։