I have a use case where I need to create say two javascript objects & use their properties in one another. eg -
var Object1 = {
settings: {
property1: 'someValue',
property2: 'someValue'
}
}
var Object2 = {
foreignProperty: Object1.settings.property1;
}
I wanted to know if its alright to use a reference object for settings if I know that I will be using the settings property a lot. eg-
var Object1Settings,
Object1 = {
settings: {
property1: 'someValue',
property2: 'someValue'
}
}
var Object1Settings = Object1.settings;
var Object2 = {
foreignProperty: Object1Settings.property1;
}
Is this approach acceptable in terms of right ways of coding & performance?
Thanks
1 Answer 1
Not only it increases readability, but such code also runs way faster.
Generally when programming I believe this is the order of priorities:
- Readibility
- CPU performance
- Saving memory
Based on this you can see, that caching any value is probably a good idea. It costs memory and saves you CPU cycles.
But I hope you do know that changing Object2.foreignProperty
will render original Object1.settings.property1
unchanged.
-
For what it's worth, I ran the tests in 3 browsers on Android.. In Chrome and Opera the cached reference was indeed fastest, but on Dolphin it was not. It was 58% slower than direct access.Mike E– Mike E2014年05月25日 21:07:13 +00:00Commented May 25, 2014 at 21:07
-
@MikeE Never heard of dolphin. I cannot explain that to you. However, I can suggest these steps for further research: Try the test once more. Don't forget that when processor is overloaded, it slows down the tests too. Second thing is to check Dolphin javascript implementation. They might be using something different than object identifier.Tomáš Zato– Tomáš Zato2014年05月25日 21:19:24 +00:00Commented May 25, 2014 at 21:19
-
I ran the test multiple times with consistent results, 57-58% slower. I'll look into reporting this to them when I'm at a desk. Also I'll look at the differences between it and the other browsers which were basically identical (Opera and Chrome).Mike E– Mike E2014年05月25日 21:40:19 +00:00Commented May 25, 2014 at 21:40
-
As of Mozilla Firefox, the results are as anticipated. For completeness, I have also ran the test in Internet Explorer which was no different from the others.Tomáš Zato– Tomáš Zato2014年05月25日 22:18:35 +00:00Commented May 25, 2014 at 22:18
-
@TomášZato thanks for the tests. results are as you have mentioned. looks good. thanks for all the help & explanation.Nitish Dhar– Nitish Dhar2014年05月26日 09:25:27 +00:00Commented May 26, 2014 at 9:25
var prop = Object1.settings.property1
Your solution does not make sense for me...