473,625 Members | 3,264 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String vs new String

I'm a bit confused by String() (typeof 'string') vs new String() (typeof
'object'). When you need to access a method or property of a -String-,
what type is JavaScript expecting (or rather, what should you provide),
a -String object- or a -string-?

Given the following benchmark:

var t = (new Date()).getTime ();
for (var ii = 0; ii < 100000; ++ii) {
var x = (String('hi')). charAt(0); // typeof 'string'
}
document.write( ((new Date()).getTime () - t) + '<br>');

var t = (new Date()).getTime ();
for (var ii = 0; ii < 100000; ++ii) {
var x = (new String('hi')).c harAt(0); // typeof 'object'
}
document.write( ((new Date()).getTime () - t) + '<br>');

Internet Explorer is consistently faster when you apply a string method
to a -String()- than a -new String()-, yet most other browsers are
consistently only slightly slower applying a method to a -String()-.
This implies to me that JavaScript in most browsers needs to take
a -string- and wrap it in a -String object- before applying the method.

Anyway, the question isn't really about performance, it's more about
proper design. Which is "more correct"?

// avoid errors for non-string types
(String(unknown Type)).replace(/something/, 'somethingElse' )
(new String(unknownT ype)).replace(/something/, 'somethingElse' )

Given that methods of String seem to return a -string- rather than
a -String object- and you can chain method calls together
(String(s)).rep lace(...).repla ce(...).replace (...) it just seems that
for "consistenc y" it's better to call your first String method on
a -string- rather than a -String object-.

Not to mention I have several functions which include code such as:

if ('string' == typeof s) {
if (/* some test on s */) return true;
}
return false;

and obviously these produce the wrong results when someone creates a
String object with new String() and passes it to my function. So I end
up refactoring the function to do something like:

if (null != s) {
if ('string' != typeof s) {
s = String(s); // s.toString() ?
}
if (/* some test on s */) return true;
}
return false;

It just all feels horribly cumbersome.

--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ - http://jibbering.com/faq
Jul 23 '05 #1
8 2787


Grant Wagner wrote:
I'm a bit confused by String() (typeof 'string') vs new String() (typeof
'object'). When you need to access a method or property of a -String-,
what type is JavaScript expecting (or rather, what should you provide),
a -String object- or a -string-? Anyway, the question isn't really about performance, it's more about
proper design. Which is "more correct"?


In my view you should always work with primitive string values so use
string literals where you want to create strings or use
String(expressi on) where you need to convert other values to primitive
string values. There is no need and no advantage in explictly creating
String object instances in your script, if a method needs to be applied
to a primitive string value the script engine will do all that is
necessary under the hood.
On the other hand if you would use String object instances you need to
be aware that you are dealing with objects where comparison is on object
identity so with

var s = 'Kibology';
new String(s) == new String(s)

the comparison yields false which is much different to the primitive
string value comparison.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #2
On 26/05/2005 14:53, Grant Wagner wrote:
I'm a bit confused by String() (typeof 'string') vs new String() (typeof
'object'). When you need to access a method or property of a -String-,
what type is JavaScript expecting (or rather, what should you provide),
a -String object- or a -string-?
It doesn't really matter as far as the language is concerned. When a
member expression (identifier.ide ntifier, or identifier[expression]) is
evaluated, the internal ToObject function is called on the left-hand
operand. For the built-in types, boolean, string, and number, this is
the same as creating a new object via the type's constructor function. So,

var value = 10,
string;

string = value.toString( 16);

is functionally equivalent to:

string = (new Number(10)).toS tring(16);

In principle, it's more efficient for you to create the object yourself
if you're going to call a method several times using the same value.
But, if the value changes between each invocation, you may as well let
the engine perform the conversion for you as the built-in objects are
immutable so a new object is needed every time anyway.
[...] I end up refactoring the function to do something like:

if (null != s) {
if ('string' != typeof s) {
s = String(s); // s.toString() ?
}
if (/* some test on s */) return true;
}
return false;


I suppose it depends on what you're doing. Sometimes I write functions
that expect either an object or a string. The former is meant to be an
element reference, whereas the latter is the id of some element - a bit
of convenience for the caller. In that situation, if an object had a
toString value that represented the id, then I'd leave it to the caller
to call toString, or use String as a function.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3
VK
You are a bit confused about primitive values and primitive value
wrappers.

var Str = "Something" ;
creates a primitive value of type "string" (so it's typeof string)

var oStr = new String("Somethi ng")
creates an object using String class as its constructor (so its typeof
"object" and oStr.constructo r = function String() {[native code]} ).

In the latter case the value itself becomes just one of properties of
this object: you need to use oStr.toSource() to get it.

It is ALWAYS more performance/resource effective to use primitives
rather than object wrappers.

The only reason to use object wrappers Object(), Boolean(), Number()
and String() would be to create customized objects with extra
properties and methods.

Jul 23 '05 #4
VK
Damn! I felt the crowd will jump on this one! :-))

Jul 23 '05 #5
"Grant Wagner" <gw*****@agrico reunited.com> wrote in message
news:yx******** ********@news2. mts.net...
I'm a bit confused by String() (typeof 'string') vs new String()
(typeof 'object'). When you need to access a method or property of
a -String-, what type is JavaScript expecting (or rather, what should
you provide), a -String object- or a -string-?


Thanks for the various replies, it confirms mostly what I already knew
(that it doesn't matter much). I mostly just wanted to hear peoples'
reasoning on one choice or another.

--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ - http://jibbering.com/faq
Jul 23 '05 #6
"VK" <sc**********@y ahoo.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
You are a bit confused about primitive values and primitive value
wrappers.
No I'm not. My question was basically: Since the underlying
implementation, when confronted with "string".charAt (0); converts this
to new String("string" ).charAt(0); is it better to do this yourself in
advance as a matter of design (without regard for performance)?
It is ALWAYS more performance/resource effective to use primitives
rather than object wrappers.
No it isn't. As I've shown, in most Web browsers it is more performant
(by a neligible margin) to wrap a string in a String object yourself
before calling a String.prototyp e method on it.

var s = 'test string';
var t = (new Date()).getTime ();
for (var ii = 0; ii < 100000; ++ii) {
var x = s.charAt(0); // typeof 'string'
}
document.write( ((new Date()).getTime () - t) + '<br>');
var t = (new Date()).getTime ();
for (var ii = 0; ii < 100000; ++ii) {
var x = (new String(s)).char At(0); // typeof 'object'
}
document.write( ((new Date()).getTime () - t) + '<br>');

In Firefox 1.0.4, Mozilla 1.7.8 and Netscape 4.78 (reduced loop counts
from 100000 to 10000) the second test (where I wrap the string in a
String object before invoking charAt() on it) has a slight (very slight)
advantage.

In Mozilla 1.0.2 and Opera 6.05, 7.54u2 and 8.00 the first test (where I
let the underlying implementation wrap it in a String object) has a
slight (very slight) advantage.

In Internet Explorer 6.0.2900 the first test has a significant advantage
(around 60% faster). I'm pretty sure it has something to do with this:
<url: http://blogs.msdn.com/ericlippert/ar...2003/11/6.aspx />

---

If "bar" is not an object then how is it possible to say

print("bar".toU pperCase());
? Well, actually, from the point of view of the specification, this is
just a syntactic sugar for

print((new String("bar")). toUpperCase());

Now, of course as an implementation detail we do not actually cons up a
new object every time you call a property on a value type! That would
be a performance nightmare. The runtime engine is smart enough to
realize that it has a value type and that it ought to pass it as the
"this" object to the appropriate method on String.prototyp e and
everything just kind of works out.

---

JScript doesn't actually "con up" a new String() everytime, the other
implementations either: a) do "con up" a new String() everytime; or b)
take longer figuring out that they don't have to.

Anyway, my question wasn't really about performance, but more about
proper design. Handle everything as a string, or as a String object, or
switch back and forth as necessary.
The only reason to use object wrappers Object(), Boolean(), Number()
and String() would be to create customized objects with extra
properties and methods.


Maybe I don't understand what you are saying, but I disagree with the
way I'm interpretting it. I don't need to wrap a string in a String
object to use custom methods/properties I've added to the String
prototype:

String.prototyp e.repeat = function(n) {
return (new Array(n + 1)).join(this);
}
alert("abc".rep eat(5));

Maybe you meant:

function MyString(s) {
var value = String(s);
this.toString = function() {
return value;
}
}
MyString.protot ype = new String();
var ms = new MyString("abc") ;
alert(ms);

But then I'm creating a MyString object, not a String object.

--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ - http://jibbering.com/faq
Jul 23 '05 #7
Grant Wagner wrote:
"VK" <sc**********@y ahoo.com> wrote [...]:
You are a bit confused about primitive values and primitive value
wrappers.
No I'm not. My question was basically: Since the underlying
implementation, when confronted with "string".charAt (0); converts this
to new String("string" ).charAt(0); is it better to do this yourself in
advance as a matter of design (without regard for performance)?


No.
It is ALWAYS more performance/resource effective to use primitives
rather than object wrappers.


No it isn't.


Yes it is.
As I've shown, in most Web browsers it is more performant
(by a neligible margin) to wrap a string in a String object yourself
before calling a String.prototyp e method on it.

var s = 'test string';
var t = (new Date()).getTime ();
for (var ii = 0; ii < 100000; ++ii) {
var x = s.charAt(0); // typeof 'string'
}
document.write( ((new Date()).getTime () - t) + '<br>');
var t = (new Date()).getTime ();
for (var ii = 0; ii < 100000; ++ii) {
var x = (new String(s)).char At(0); // typeof 'object'
}
document.write( ((new Date()).getTime () - t) + '<br>');
Loops: 100
Repeats: 10

Result:
--------

Expressions:

[1] "foo".charA t(0)
[2] new String("foo").c harAt(0)

Evaluation Results (ms):

\n| 1 2 3 4 5 6 7 8 9 10 min max avg
e\|____________ _______________ ___
1| 34 55 54 33 55 31 55 32 53 32 31 55 43.4
2| 57 57 35 59 56 36 89 37 57 55 35 89 53.8

User Agent:
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.8) Gecko/20050517
Firefox/1.0.4 (Debian package 1.0.4-2) Mnenhy/0.7.2.0

Although this is still a singular result, the second expression in the
average always took more time to be evaluated than the first one, in all
of the 10 tests of the 10 x 100 loops performed.
In Firefox 1.0.4, [...] (reduced loop counts from 100000 to 10000) the
second test (where I wrap the string in a String object before invoking
charAt() on it) has a slight (very slight) advantage.


I cannot second that.
PointedEars
Jul 23 '05 #8
On 02/06/2005 18:31, Thomas 'PointedEars' Lahn wrote:

[snip]
[1] "foo".charA t(0)
[2] new String("foo").c harAt(0)


[snip]

If you're merely evaluating one-time object instances, then the latter
will always be slower due to the overhead involved in the NewExpression.
I implied that much in my post. However, if the same object instance can
be used multiple times, then it will be quicker as there is no need to
create an intermediary. Evaluating new String(...) outside the inner
test loop should demonstrate this. I see an improvement of about 62%.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
6724
by: Krakatioison | last post by:
My sites navigation is like this: http://www.newsbackup.com/index.php?n=000000000040900000 , depending on the variable "n" (which is always a number), it will take me anywhere on the site... this number is always changing as I have hundreds of thousand of pages of text on my site. Problem: - in my opinion this just not only look weird, but the variable "n" (number)
5
31171
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it will split myString up using the delimiter of 1 space so that
9
7994
by: John F Dutcher | last post by:
I use code like the following to retrieve fields from a form: recd = recd.append(string.ljust(form.getfirst("lname",' '),15)) recd.append(string.ljust(form.getfirst("fname",' '),15)) etc., etc. The intent is to finish by assigning the list to a string that I would write to disk: recstr = string.join(recd,'')
10
8162
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is effectively impossible to forward declare std::string. (Yes I am aware that some libraries have a string_fwd.h header, but this is not portable.) That said, is there any real reason why I can't derive an otherwise empty
2
4771
by: Andrew | last post by:
I have written two classes : a String Class based on the book " C++ in 21 days " and a GenericIpClass listed below : file GenericStringClass.h // Generic String class
29
4301
by: zoro | last post by:
Hi, I am new to C#, coming from Delphi. In Delphi, I am using a 3rd party string handling library that includes some very useful string functions, in particular I'm interested in BEFORE (return substring before a pattern), AFTER (return substring after a pattern), and BETWEEN (return substring between 2 patterns). My questions are: 1. Can any tell me how I can implement such functionality in C#? 2. Is it possible to add/include function...
2
3171
by: Badass Scotsman | last post by:
Hello, Using VB and ASP,NET I would like to be able to search a STRING for a smaller STRING within, based on the characters which appear before and after. For example: String1 = " That was a tasty burger"
15
50214
by: morleyc | last post by:
Hi, i would like to remove a number of characters from my string (\t \r \n which are throughout the string), i know regex can do this but i have no idea how. Any pointers much appreciated. Chris
11
3055
by: ramu | last post by:
Hi, Suppose I have a string like this: "I have a string \"and a inner string\\\" I want to remove space in this string but not in the inner string" In the above string I have to remove spaces, but not in the inner string(\"and a inner string\\\"). Will anyone please tell me how to do this?
8
4733
by: drjay1627 | last post by:
hello, This is my 1st post here! *welcome drjay* Thanks! I look answering questions and getting answers to other! Now that we got that out of the way. I'm trying to read in a string and add the unique words in the string to a map. Eg:
0
8189
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8694
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8356
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8497
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6118
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4089
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2621
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.