Difference Between String Object and String Literal

What is the difference between string literals and string values?

A string literal is a piece of text you can write in your program's source code, beginning and ending with quotation marks, that tells Python to create a string with certain contents. It looks like

'asdf'

or

'''
multiline
content
'''

or

'the thing at the end of this one is a line break\n'

In a string literal (except for raw string literals), special sequences of characters known as escape sequences in the string literal are replaced with different characters in the actual string. For example, the escape sequence \n in a string literal is replaced with a line feed character in the actual string. Escape sequences begin with a backslash.


A string is a Python object representing a text value. It can be built from a string literal, or it could be read from a file, or it could originate from many other sources.

Backslashes in a string have no special meaning, and backslashes in most possible sources of strings have no special meaning either. For example, if you have a file with backslashes in it, looking like this:

asdf\n

and you do

with open('that_file.txt') as f:
text = f.read()

the \n in the file will not be replaced by a line break. Backslashes are special in string literals, but not in most other contexts.


When you ask for the repr representation of a string, either by calling repr or by displaying the string interactively:

>>> some_string = "asdf"
>>> some_string
'asdf'

Python will build a new string whose contents are a string literal that would evaluate to the original string. In this example, some_string does not have ' or " characters in it. The contents of the string are the four characters asdf, the characters displayed if you print the string:

>>> print(some_string)
asdf

However, the repr representation has ' characters in it, because 'asdf' is a string literal that would evaluate to the string. Note that 'asdf' is not the same string literal as the "asdf" we originally used - many different string literals can evaluate to equal strings.

What is the difference between string primitives and String objects in JavaScript?

JavaScript has two main type categories, primitives and objects.

var s = 'test';
var ss = new String('test');

The single quote/double quote patterns are identical in terms of functionality. That aside, the behaviour you are trying to name is called auto-boxing. So what actually happens is that a primitive is converted to its wrapper type when a method of the wrapper type is invoked. Put simple:

var s = 'test';

Is a primitive data type. It has no methods, it is nothing more than a pointer to a raw data memory reference, which explains the much faster random access speed.

So what happens when you do s.charAt(i) for instance?

Since s is not an instance of String, JavaScript will auto-box s, which has typeof string to its wrapper type, String, with typeof object or more precisely s.valueOf(s).prototype.toString.call = [object String].

The auto-boxing behaviour casts s back and forth to its wrapper type as needed, but the standard operations are incredibly fast since you are dealing with a simpler data type. However auto-boxing and Object.prototype.valueOf have different effects.

If you want to force the auto-boxing or to cast a primitive to its wrapper type, you can use Object.prototype.valueOf, but the behaviour is different. Based on a wide variety of test scenarios auto-boxing only applies the 'required' methods, without altering the primitive nature of the variable. Which is why you get better speed.

difference of String object, and string literal in JavaScript

They differ. A string literal is a primitive value, while a "String" instance is an object. The primitive string type is promoted automatically to a String object when necessary.

Similarly, there are numeric primitives and "Number" instances, and boolean primitives and "Boolean" instances.

whats the difference between string literals, and just a string?

A literal string (or literal <any data type>) means that you just reference the data directly.

For example

"Hello".length // returns 5

The "Hello" is a string literal since we are just referencing it "as-is".
You could do exactly the same thing with a string object:

var strObj = new String("Hello");
strObj.length // returns 5

These two examples are pretty much identical (for the sake of this example). Both create a string variable and measure it's length.
The first uses a string literal and the second uses a string object.


Here is another example using numbers - if you do a direct calculation such as:

5 + 2

you'll be using number literals - again, when you only reference the data directly, it is considered a "literal".

What's the difference between String.new and a string literal in Ruby?

== checks for equal content.

equal? checks for equal identity.

a = "hello"
b = "hello"

a == b # => true
a.equal?(b) # => false

In Ruby string literals are not immutable and thus creating a string and using a literal are indeed the same. In both cases Ruby creates a new string instance each time the expressions in evaluated.

Both of these are thus the same

10.times { String.new }
# is the same as
10.times { "" }

Let's verify this

10.times { puts "".object_id }

Prints 10 different numbers

70227981403600
70227981403520
70227981403460
...

Why? Strings are by default mutable and thus Ruby has to create a copy each time a string literal is reached in the source code. Even if those literals are usually rarely modified in practice.

Thus a Ruby program typically creates an excessive amount short-lived string objects, which puts a huge strain on garbage collection. It is not unusual that a Rails app creates 500,000 short-lived strings just to serve one request and this is one of the main performance bottlenecks of scaling Rails to millions or even 100 millions of users.

To address that Ruby 2.3 introduced frozen string literals, where all string literals default to being immutable. Since this is not backwards compatible it is opt-in with a pragma

# frozen_string_literal: true

Let's verify this too

# frozen_string_literal: true
10.times { puts "".object_id }

Prints the same number 10 times

69898321746880
69898321746880
69898321746880
...

Fun fact, setting a key in a hash also creates a copy of a string

str = "key"
hash = {}
hash[str] = true
puts str.object_id
puts hash.keys.first.object_id

Prints two different numbers

70243164028580
70243132639660

String Literal vs String Object

Whenever new Keyword is used then object is created in heap.
Here new Keyword is not used so string object is created in string pool.

For example:

String s1= new String("string object");

In the above example two objects are being created one is string object in string pool since it is in double quotes another is s1 which is created in heap as new keyword is used.



Related Topics



Leave a reply



Submit